javascript - React 组件构造函数和 componentWillReceiveProps 中的常用代码

标签 javascript reactjs single-page-application

在使用有状态的 React 组件时,我经常遇到这种情况。

我需要对 props 做一些操作 - 要么做一些我现在想在 render() 中进行的处理,要么根据 props 中的值设置状态。

因为我想在最初安装组件时以及更新 props 时执行此操作,所以我最终得到了这样的样板代码:

constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

有没有更好的方法来做到这一点?

最佳答案

根据问题的评论回答,我觉得很有帮助 --

如果有一堆工作需要根据props来完成,componentWillMount允许你使用this.setState()您的辅助函数并最大限度地减少在 constructor 中完成的工作。这可以清理一堆重复的代码。

constructor(){
    super(props)
    this.state = {initialState}
}

componentWillMount() {
    this.doSomethingWithProps(this.props);
}

componentWillReceiveProps(nextProps) {
    this.doSomethingWithProps(nextProps)
}

doSomethingWithProps(props){
    ...
    this.setState({newState})
}

关于javascript - React 组件构造函数和 componentWillReceiveProps 中的常用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436526/

相关文章:

javascript - 如何在页面中搜索单词并突出显示它们(JQuery)

Javascript正则表达式如何获取字符串中两个单词之间的所有出现次数

javascript - 关闭未使用变量的内存泄漏

reactjs - React : why is double brace syntax, style{{..}},内联样式必需

angular - AMP(加速移动页面)是否与 angular2 兼容?

security - 身份验证和 session 管理的 SPA 最佳实践

javascript - 如何为组合框赋值

javascript - react 上下文奇怪的数据类型错误

javascript - 从网格中过滤记录时出错

authentication - 如何在sails.js SPA 上处理多个身份验证策略?