在Navigator中更新组件后获取警告

时间:2016-07-12 19:55:30

标签: react-native redux

我的React Native应用程序中有一个容器,并且在我从服务器获取数据之前,我像preload一样使用它来显示场景Loading...。所以我发送了一个动作来获取用户数据,之后我更新了我的状态,我尝试将新组件推送到Navigator但是我遇到了错误:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

我不明白解决问题的最佳方法是什么。

所以我的容器:

import myComponent from '../components'

class App extends Component {
  componentDidMount() {
    this.props.dispatch(fetchUser());
  }

  _navigate(component, type = 'Normal') {
    this.props.navigator.push({
      component,
      type
    })
  }

  render() {
    if (!this.props.isFetching) {
      this._navigate(myComponent);
    }

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Loading...
        </Text>
      </View>
    );
  }
}
App.propTypes = {
  dispatch: React.PropTypes.func,
  isFetching: React.PropTypes.bool,
  user: React.PropTypes.string
};

export default connect((state) => ({
  isFetching: state.data.isFetching,
  data: state.data.user
}))(App);

我的减速机:

const data = (state = initialState, action) => {
  switch (action.type) {
    case types.USER_FETCH_SUCCEEDED:
      return {
        ...state,
        isFetching: false,
        user: action.user
      };
    default:
      return state;
  }
};

1 个答案:

答案 0 :(得分:1)

不要触发setState方法体内render内的任何内容。如果您需要收听传入的道具,请使用componentWillReceiveProps

render()

中删除此内容
if (!this.props.isFetching) {
  this._navigate(myComponent);
}

并添加componentWillReceiveProps(nextProps)

componentWillReceiveProps(nextProps) {
  if (!nextProps.isFetching) {
    this._navigate(myComponent);
  }
}