简体   繁体   English

React-redux初始化函数,无论状态如何变化

[英]React-redux initialization function regardless of state changes

I really don't know how to describe as precise as possible. 我真的不知道如何描述尽可能精确。 I need some sort of initialization function after async call, that would be called only once regardless if state is changed later. 我需要在异步调用之后使用某种初始化函数,无论稍后是否更改状态,都只会调用一次。

I have a component and when it mounts I make async request using action creator to get some default values, also I call somethingElse() later, which makes my UI re-render again because the state was updated: 我有一个组件,当它安装时,我使用动作创建器创建异步请求以获取一些默认值,我稍后调用somethingElse() ,这使得我的UI再次重新渲染,因为状态已更新:

Here is action creator: 这是动作创建者:

export function requestDefaults(){    
  return {
    type:     REQUEST_DEFAULTS,
    payload:  axios.get(ROOT_URL),
  };
}

export function somethingElse(){    
  return {
    type:     SOME_OTHER,
    payload:  "Whatever",
  };
}

And my reducer: 而我的减速机:

switch (action.type) {
    case REQUEST_DEFAULTS:
      return action.payload.data;
      break;

    case SOME_OTHER:
      return action.payload;
      break;

    default:
      return state;
}

In my component - when it's maunted I make async request and when I receive response I make UI visible - in this simplified case a button, which calls somethingElse : 在我的组件中 - 当它被捣乱时,我发出异步请求,当我收到响应时,我使UI可见 - 在这个简化的情况下,一个按钮,调用somethingElse

componentDidMount(){
   this.props.requestDefaults();
 }


render(){
  // Have received async data show button - THIS NEEDS TO BE ONLY ONCE
  if( this.props.defaults.data !== undefined ){
     <a onClick={ this.props.someThingElse }>do it</a>
  }
}

// REQUEST_DEFAULTS & SOME_OTHER
function mapStateToProps( { defaults, someOther} ){
  return { defaults, someOther} 
}

Now whenever I call this.props.someThingElse the changes to the state are made and in my render() function the button gets re-rendered again, which is the problem - I need it to be rendered only once, when I receive the async data. 现在每当我调用this.props.someThingElse时,都会对状态进行更改,并且在我的render()函数中,按钮会再次重新渲染,这就是问题 - 当我收到异步时,我只需要渲染一次数据。 But now state was updated and render() is called again and because now I have this.props.defaults.data my button gets re-rendered again, but I need it to be done only once after first async call and not when state changes later... 但是现在状态已经更新并且render()再次被调用,因为现在我有了this.props.defaults.data我的按钮再次被重新渲染,但是我需要在第一次异步调用后才进行一次,而不是在状态发生变化时后来...

You could use shouldComponentUpdate method and re render only if default data was changed. 您可以使用shouldComponentUpdate方法,仅在更改默认数据时重新呈现。 In your case default data change only once (by default it is empty on the next step has some data), so render method will be called only once. 在您的情况下,默认数据只更改一次(默认情况下,下一步有一些数据时为空),因此只调用一次render方法。

shouldComponentUpdate(nextProps, nextState) {
  return this.props.defaults.data !== nextProps.this.props.defaults.data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM