How to make a shared state between two react components?

前端 未结 5 498
盖世英雄少女心
盖世英雄少女心 2020-11-27 07:04

I have 2 react components that need to share a state, react-router shows component A, which takes some inputs and adds it to its state, after the state has been successfully

5条回答
  •  失恋的感觉
    2020-11-27 07:11

    You can build custom React hooks to share a state between components, I made one here. You can use it by downloading use-linked-state.js file.

    After importing useStateGateway hook, declare a gateway in parent component and pass it down to your child components

    import {useStateGateway} from "use-linked-state";
    const myGateway = useStateGateway({partA:null, partB:null});
    return (
      <>
        
        
        
      
      )
    
    

    Then you have access shared state between those three components by a custom useLinkedState hook

    import { useLinkedState } from "use-linked-state";
    
    export default function ComponentA({gateway}){
    
      const [state, setState] =  useLinkedState(gateway);
    
      
    
    }
    

    In your logic ComponentA and ComponentB would be responsible for their part in shared object {partA:"filled by ComponentA", partB:"filled by componentB"}. Finally ComponentPost post the result if partA and partB of shared object were valid.

    In this way you can compose components and make connection between them to talk to each other.

提交回复
热议问题