考虑到下面的组件结构,我不想更新我的父级状态,然后应该更新我的GrandChild。我知道我可以使它工作,使儿童无国籍或只更新国家在儿童,但在我们的应用程序,这是目前的结构。有什么好办法来做这件事吗?还是我们应该重新设计?我们在父级中保持状态,因为我们不想向应用程序中的许多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发布于 2017-10-31 21:37:11
这里的问题是,您正在将道具映射到状态,一旦发生这种情况,您就是负责在道具更改时更新状态的人。因为您只使用componentDidMount,所以它只将道具映射为状态一次。我通常倾向于避免让组件将道具转换为自己的状态,而只是让父组件以它需要的任何方式将道具传递给子组件,而不必担心当道具在子组件中发生变化时更改状态。
另一个选项是使用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将处理更改状态。
https://stackoverflow.com/questions/47044223
复制相似问题