繁体   English   中英

React js访问另一个类的状态

[英]React js access to the state of another class

如何访问另一个类的状态。
这种结构不起作用

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

如评论中所述,将状态作为道具传递给孩子。

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>
    );
  }
};

一种常用的模式是将任意props传递到组件树下:

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

钩子的更新,因为为什么不这样。

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

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

通过直接访问在组件之间共享状态是一种反模式。 每个组件应具有其自己的状态。 如果您需要全局可用状态,请考虑使用Redux

乍一看可能有点麻烦,但是它很棒,并且可以正确测试您的应用程序。

编辑

将状态作为prop传递也是有效的,但是仅当组件处于父子顺序时才有效。 Redux允许更新组件,无论它们之间的关系如何

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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