gpt4 book ai didi

reactjs - React - componentWillReceiveProps 替代方案

转载 作者:行者123 更新时间:2023-12-03 13:01:12 41 4
gpt4 key购买 nike

我将 React 与 NextJS 结合使用。

我有一个组件,它基本上是一个提供一些摘要的表格。根据一些 UI 选择,该组件预计会显示适当的摘要。

下面的代码工作得很好。

class Summary extends Component{

state = {
total: 0,
pass: 0,
fail: 0,
passp: 0,
failp: 0
}

componentWillReceiveProps(props){
let total = props.results.length;
let pass = props.results.filter(r => r.status == 'pass').length;
let fail = total - pass;
let passp = (pass/(total || 1) *100).toFixed(2);
let failp = (fail/(total || 1) *100).toFixed(2);
this.setState({total, pass, fail, passp, failp});
}

render() {
return(
<Table color="teal" >
<Table.Header>
<Table.Row textAlign="center">
<Table.HeaderCell>TOTAL</Table.HeaderCell>
<Table.HeaderCell>PASS</Table.HeaderCell>
<Table.HeaderCell>FAIL</Table.HeaderCell>
<Table.HeaderCell>PASS %</Table.HeaderCell>
<Table.HeaderCell>FAIL %</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row textAlign="center">
<Table.Cell>{this.state.total}</Table.Cell>
<Table.Cell >{this.state.pass}</Table.Cell>
<Table.Cell >{this.state.fail}</Table.Cell>
<Table.Cell >{this.state.passp}</Table.Cell>
<Table.Cell >{this.state.failp}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
);
}
}

看起来像componentWillReceiveProps将被弃用。我尝试了其他选项,例如 shouldComponentUpdate等等......它们都会导致无限循环。从 props 更新状态以重新渲染此组件的最佳方法是什么?

最佳答案

来自 react blog ,16.3 引入了 componentWillRecieveProps 的弃用通知。

作为解决方法,您可以使用以下方法

static getDerivedStateFromProps(nextProps, prevState)

因此

componentWillReceiveProps(props){
let total = props.results.length;
let pass = props.results.filter(r => r.status == 'pass').length;
let fail = total - pass;
let passp = (pass/(total || 1) *100).toFixed(2);
let failp = (fail/(total || 1) *100).toFixed(2);
this.setState({total, pass, fail, passp, failp});
}

变成了

static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.total !== prevState.total) {
return ({ total: nextProps.total }) // <- this is setState equivalent
}
return null
}

关于reactjs - React - componentWillReceiveProps 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692160/

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