簡體   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