reactjs - 当状态第一次更新时,componentWillReceiveProps 不会触发

标签 reactjs react-native react-redux

我有两个不相关的组件连接到 redux。一个是按钮,另一个是应用程序的主屏幕。该计划是让 HomeScreen 知道何时单击该按钮。因此,我有一个操作和一个 reducer 来传递按钮的状态。除了当我第一次单击该按钮时主屏幕没有接收更新之外,这工作正常。我必须单击按钮两次才能使状态恢复正常。

添加事件操作:

import { PLUS_INCIDENT } from './types';

export const plusIncident = pressed => (dispatch) => {
  console.log('2: action: ', pressed);
  dispatch({
    type: PLUS_INCIDENT,
    payload: pressed
  });
};

按钮组件:

// The action
import { plusIncident } from '../redux/actions/plusIncident';

import { connect } from 'react-redux';

class AddIncidentButton extends Component {
  handleAddButtonPress = () => {
    const { pressed } = this.state;
    const { plusIncident } = this.props;

    const btnState = !pressed;
    this.setState({ pressed: btnState });
    plusIncident(btnState);
  };
...

}
...
export default connect(
  null,
  { plusIncident }
)(AddIncidentButton);

reducer :

import { PLUS_INCIDENT } from '../actions/types';

const initialiState = {
  pressed: false
};

function inc(state = initialiState, action) {
  switch (action.type) {
    case PLUS_INCIDENT:
      return {
        ...state,
        pressed: !action.payload
      };
    default:
      return state;
  }
}

主屏幕: componentWillReceiveProps 方法仅在单击按钮两次后才会被调用。

class HomeScreen extends React.Component {
  state = {
    pressed: false
  };

 componentWillReceiveProps(nextProps) {
    const { pressed } = this.props;
    if (pressed !== nextProps.pressed) {
      this.setState({ pressed: !nextProps.pressed });
    }
  }
...
}

const mapStateToProps = state => ({
  pressed: state.inc.pressed
});
export default connect(mapStateToProps)(HomeScreen);

最佳答案

尝试添加首次调用的 componentDidMount() 。收到更新后将调用 componentWillRecieveProps:

componentDidMount() {
      this.setState({ pressed: !this.props.pressed});
}

希望它有效..

关于reactjs - 当状态第一次更新时,componentWillReceiveProps 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439888/

相关文章:

cakephp - 在 CakePHP 项目中设置 React

javascript - Jest +酵素。无法读取未定义的属性 '_isMockFunction'。模拟箭头的keyDown

javascript - 条件渲染不显示 - ReactJS

React-Native:如何打开本地捆绑的二进制文件

push-notification - Android onNotification 从未在 react-native-push-notification 中调用

javascript - 来自 mapStateToProps 的 Redux 形式初始值

node.js - 如何在 Cookie 上指定 SameSite 和 Secure(使用 axios/React/Node Express)

javascript - 每当我移动到不同的标签屏幕时,它都会显示错误 "Accessing the state property of the route object is not supported"

javascript - Redux-saga如何向saga内部请求传递参数

reactjs - 在带有react-router-v4的 Action 创建器中使用history.push?