简体   繁体   中英

React js access to the state of another class

How can I access the state of another class.
This construction does not work

 class classname2 extends React.Component { ... this.state = { statename1: "lala" }; ... }; class classname1 extends React.Component { render() { return ( {classname2.state.statename1 } ); } }; 

As mentioned in the comments, pass state as props to their children.

class classname2 extends React.Component {
  this.state = { statename1: "lala" };
  render() {
    return <classname1 statename1={this.state.statename1} />
  }
};

class classname1 extends React.Component {
  render() {
    return (
       <div>{this.props.statename1}</div>
    );
  }
};

An often used pattern is passing arbitrary props down the component tree:

const {needThisOne, andThisOne, ...props} = this.props;
// do stuff with needThisOne andThisOne
// and pass the remaining props down:
return <Component {...props} />;

An update for hooks, because why not.

const ParentComponent = ({...props}) => {
   const [stateName1, setStateName1] = useState('defaultValue');
   return <ChildComponent stateName1={stateName1} {...props} />;
}

const ChildComponent = ({stateName1, ...props}) => (
    <span>{stateName1}</span>
);

Shared state between components by direct access is an anti-pattern. Each component should have its own state. If you need globally a available state, please consider using Redux .

It may sound a bit cumbersome at first but it's awesome and it allows your app to be properly tested.

Edit :

Passing state as props is also valid, but it only works when components are in parent-child order. Redux allows components to be updated no matter what their relationship is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM