[英]React 16.0.0 Parent Child GrandChild. Updating state in Parent does not update GrandChild
鑒於以下組件結構,我不想在Parent中更新我的狀態,然后應該更新我的GrandChild。 我知道我可以使它工作使Child無狀態或只更新Child中的State但在我們的應用程序中這是當前的結構。 有沒有什么好方法可以做到這一點,還是我們應該重新設計? 我們在父級中保持狀態,因為我們不想在應用程序中發出許多http請求。 在父級中,我們獲取所需的數據並進行初始修改。 然后將這些數據發送到其他組件,而這些組件又具有子組件,因此是示例結構。
在此示例中打印的內容: Test: 1235
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps {
}
interface IState {
cases: number[];
}
class Parent extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
cases: [1, 2, 3],
};
}
componentDidMount() {
let newCase = 4;
let newCases = Array.from(this.state.cases);
newCases.push(newCase)
this.setState({
cases: newCases
});
}
render() {
return (
<div>
<Child cases={this.state.cases} />
</div>
);
}
}
interface IChildProps {
cases: number[];
}
interface IChildState {
cases: number[];
}
class Child extends React.Component<IChildProps, IChildState> {
constructor(props: IChildProps) {
super(props);
this.state = {
cases: this.props.cases,
};
}
componentDidMount() {
let newCase = 5;
let newCases = Array.from(this.state.cases);
newCases.push(newCase)
this.setState({
cases: newCases
});
}
render() {
return (
<GrandChild cases={this.state.cases} />
);
}
}
interface IGrandChildProps {
cases: number[];
}
interface IGrandChildState {
}
class GrandChild extends React.Component<IGrandChildProps, IGrandChildState> {
constructor(props: IGrandChildProps) {
super(props);
}
render() {
return (
<div>
Test: {this.props.cases.map((value, index) => {
return <span key={index}>{value}</span>
}
)}
</div>
);
}
}
export default Parent
這里的問題是你將道具映射到狀態,一旦發生這種情況,你就是在道具改變時負責更新狀態的人。 由於您只使用componentDidMount
因此它只將props映射到狀態一次。 我通常傾向於避免讓組件將道具轉換為自己的狀態,而只是讓父母以任何需要的方式將道具傳遞給孩子,而不必擔心在子組件中道具改變時改變狀態。
另一種選擇是使用componentWillReceiveProps
生命周期方法並執行以下操作
setCases(cases) {
let newCase = 5;
let newCases = Array.from(cases);
newCases.push(newCase)
this.setState({
cases: newCases
});
}
componentDidMount() {
this.setCases(this.props.cases)
}
componentWillReceiveProps(nextProps) {
this.setCases(nextProps.cases);
}
componentDidMount
將處理在初始加載時設置狀態,然后componentWillReceiveProps
將處理在props更改時更改狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.