gpt4 book ai didi

javascript - React 16.0.0 父子孙子。更新 Parent 中的状态不会更新 GrandChild

转载 作者:行者123 更新时间:2023-11-30 11:28:47 25 4
gpt4 key购买 nike

鉴于以下组件结构,我不想更新我在 Parent 中的状态,这应该会更新我的 GrandChild。我知道我可以让它工作,使 Child 无状态或仅更新 Child 中的状态,但在我们的应用程序中,这是当前结构。有什么好的方法可以做到这一点还是我们应该重新设计?我们在父级中保留一个状态,因为我们不想在应用程序中发出许多 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

最佳答案

这里的问题是您正在将 props 映射到状态,一旦发生这种情况,您就是负责在 props 更改时更新状态的人。由于您只使用 componentDidMount 它只将 Prop 映射到状态一次。我通常倾向于避免让组件将 props 转换为它自己的状态,而只是让父组件以任何需要的方式将 props 传递给子组件,而不必担心在子组件中的 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 更改时处理更改状态。

关于javascript - React 16.0.0 父子孙子。更新 Parent 中的状态不会更新 GrandChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com