reactjs – React – componentWillReceiveProps替代

前端之家收集整理的这篇文章主要介绍了reactjs – React – componentWillReceiveProps替代前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps1个
我将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更新状态以重新渲染此组件的最佳方法是什么?

从反应 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,failp});
}

static getDerivedStateFromProps(nextProps,prevState) {
  if (nextProps.total !== prevState.total) {
    return ({ total: nextProps.total }) // <- this is setState equivalent
  }
  etc...
}
原文链接:https://www.f2er.com/react/300713.html

猜你在找的React相关文章