有什么方法可以检查构造器属性是否已更改,然后在React中重新渲染组件?

时间:2018-09-24 13:37:25

标签: reactjs

我有一个问题,有什么办法可以检查构造函数prop是否在会话存储中以及根据该重新渲染组件进行了更改?

示例:

export class MainPage extends React.Component {
  constructor(props) {
    super(props);
    this.channelId = sessionStorage.getItem('channelId');
    };
  }
    componentDidMount() {
      fetch(`http://url.com/${this.channelId}`,     
            {
             method: 'GET'
            },
           )
    }

编辑:将项目添加到会话存储的示例:

export class ChannelItem extends React.PureComponent {
  constructor() {
    super();

    this.state = {
      channelChange: false,
    };

    this.channelChange = this.channelChange.bind(this);
  }

  channelChange() {
    this.setState({ channelChange: true });
  }

  render() {
    const { item } = this.props;

    if (this.state.channelChange) {
      sessionStorage.setItem('channelId', item.channelId);    
    });
  }
}

2 个答案:

答案 0 :(得分:0)

是的,当道具发生更改或更新时,您可以使用componentWillReceiveProps(){}生命周期方法

答案 1 :(得分:0)

当道具更改或状态更新时,React将自动重新渲染。因此,在您的情况下,最简单的解决方案是将sessionStorage变量作为对MainPage的支持。可以通过将该状态提升到容器组件来实现

export class MainPage extends React.Component {
    componentDidMount() {
      fetch(`http://url.com/${this.props.channelId}`,     
            {
             method: 'GET'
            },
           )
    }

    //This lifecycle method gets called every time props or state change
    componentDidUpdate(prevProps) {
      if (prevProps.channelId !== this.props.channelId) {
        fetch(`http://url.com/${this.props.channelId}`,     
            {
             method: 'GET'
            },
           )
      }
    }
    //...
}

export class ChannelItem extends React.PureComponent {
  constructor() {
    super();

    this.state = {
      channelChange: false,
    };

    this.channelChange = this.channelChange.bind(this);
  }

  channelChange() {
    sessionStorage.setItem('channelId', item.channelId); 
    // after setting the sessionStorage value, you call back the parent component to update its state, triggering the rerender
    this.props.onChannelChange();
  }
  //...
}

class SomeContainerComponent extends Component {
  constructor(props) {
    this.state = {
      channelId: sessionStorage.getItem('channelId'),
    }
  }

  onSessionChange = () => {
    this.setState({ channelId: sessionStorage.getItem('channelId') });
  }

  render() {
    return (
      <div>
       <MainPage channelId={this.state.channelId} />
       <ChannelItem onChannelChange={this.onSessionChange} />
      </div>
    )
  }

}