[英]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: 一种常用的模式是将任意props传递到组件树下:
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 . 如果您需要全局可用状态,请考虑使用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. 将状态作为prop传递也是有效的,但是仅当组件处于父子顺序时才有效。 Redux allows components to be updated no matter what their relationship is Redux允许更新组件,无论它们之间的关系如何
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.