React-componentWillReceiveProps替代品
我将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
它们都导致无限循环。从道具更新状态以重新渲染此组件的最佳方法是什么?
回答:
从react 博客开始,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
}
以上是 React-componentWillReceiveProps替代品 的全部内容, 来源链接: utcz.com/qa/413554.html