我正在使用setState()更新父组件的状态,并已将状态参数传递给子组件之一,但是当状态更改时,子组件不会重新呈现。
这是我的代码设置:
1)父组件(它计算完成的任务(请参阅第3点)并将其传递给子组件)
class ParentComponent extends Component {
constructor() {
super();
this.state = {
tasks: Tasks,
completed: 0
}
}
async componentDidMount() {
this.setState((prevState)=>{
// calculate completed tasks
prevState.completed = prevState.tasks.reduce((total,curr) => total + (curr.completed?1:0),0);
return prevState;
});
}
render() {
return (
<div>
<ChildComponent counter={this.state.completed}/>
</div>
);
}
}
2)子组件(显示从父级传递来的已完成任务的数量)
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
"counter": this.props.counter
}
}
render() {
return (
<div>
<h1>{this.state.counter}</h1>
</div>
)
}
}
3)任务是从文件中导入的,就像这样:
const tasks = [
{
id: 1,
completed: true
},
{
id: 2,
completed: false
}
]
发生什么情况,计数器保持为0。为什么不更新为1?
答案 0 :(得分:0)
您可以在子组件中尝试两种方式
class ChildComponent extends Component {
render() {
return (
<div>
<h1>{this.props.counter}</h1>
</div>
)
}
}
或尝试
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
componentDidUpdate(prevProps){
if (this.props.counter !== prevProps.counter) {
this.setState({counter: this.props.counter})
}
render() {
return (
<div>
<h1>{this.state.counter}</h1>
</div>
)
}
}