道具更改时重新渲染React组件

React.js

阿飞小卤蛋

2020-03-16

我正在尝试将表示性组件与容器组件分开。我有一个SitesTable和一个SitesTableContainer容器负责触发redux操作,以根据当前用户获取适当的网站。

问题是在最初呈现容器组件之后,异步获取了当前用户。这意味着容器组件不知道它需要重新执行其componentDidMount函数中的代码,该代码将更新数据以发送到SitesTable我想我需要在其props(user)之一更改时重新渲染容器组件。如何正确执行此操作?

class SitesTableContainer extends React.Component {
    static get propTypes() {
      return {
        sites: React.PropTypes.object,
        user: React.PropTypes.object,
        isManager: React.PropTypes.boolean
      }
     }

    componentDidMount() {
      if (this.props.isManager) {
        this.props.dispatch(actions.fetchAllSites())
      } else {
        const currentUserId = this.props.user.get('id')
        this.props.dispatch(actions.fetchUsersSites(currentUserId))
      }  
    }

    render() {
      return <SitesTable sites={this.props.sites}/>
    }
}

function mapStateToProps(state) {
  const user = userUtils.getCurrentUser(state)

  return {
    sites: state.get('sites'),
    user,
    isManager: userUtils.isManager(user)
  }
}

export default connect(mapStateToProps)(SitesTableContainer);

第1716篇《道具更改时重新渲染React组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
番长阿飞 2020.03.16

以下是一种易于使用的方法,道具更新后,它将自动重新渲染组件:

render {

let textWhenComponentUpdate = this.props.text 

return (
<View>
  <Text>{textWhenComponentUpdate}</Text>
</View>
)

}
猿米亚 2020.03.16

您可以使用KEY随道具更改的唯一键(数据组合),并且该组件将使用更新的道具重新呈现。

小卤蛋小卤蛋 2020.03.16

ComponentWillReceiveProps()由于错误和不一致,将来将不推荐使用。在props更改时重新渲染组件的替代解决方案是使用ComponentDidUpdate()ShouldComponentUpdate()

ComponentDidUpdate()每当组件更新时调用,并且if ShouldComponentUpdate()返回true(如果ShouldComponentUpdate()未定义,则true默认情况下返回)。

shouldComponentUpdate(nextProps){
    return nextProps.changedProp !== this.state.changedProp;
}

componentDidUpdate(props){
    // Desired operations: ex setting state
}

可以ComponentDidUpdate()通过在其中包含条件语句来仅使用该方法来实现相同的行为

componentDidUpdate(prevProps){
    if(prevProps.changedProp !== this.props.changedProp){
        this.setState({          
            changedProp: this.props.changedProp
        });
    }
}

如果尝试在没有条件或没有定义ShouldComponentUpdate()组件的情况下设置状态,则组件将无限地重新渲染

小胖Gil 2020.03.16
componentWillReceiveProps(nextProps) { // your code here}

我认为那是您需要的事件。componentWillReceiveProps每当您的组件通过道具收到东西时触发。从那里您可以进行检查,然后做您想做的任何事情。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android