React - componentWillReceiveProps替代方案

时间:2018-06-05 04:40:57

标签: reactjs nextjs

我将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>             
        );
    }
}

看起来{@ 1}}将被弃用。我尝试了其他选项,如componentWillReceiveProps等等。这些都导致无限循环。从props更新状态以重新渲染此组件的最佳方法是什么?

1 个答案:

答案 0 :(得分:24)

从反应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
  }
  etc...
}