React + Redux:未定义的初始状态和reducer未按预期调用

时间:2017-12-06 16:41:28

标签: reactjs redux

我认为这很原始。我遇到两件事有困难:

1. this.props.appState在构造函数中是undefined。这是意料之外的,因为在reducer中我将初始状态设置为{ appState: { name: "World!" } },并且我期望这导致appState的初始化。所以我在发现实际问题之前添加了if语句,我知道这只是一个临时修复。

2.当我点击按钮并调用sendAction处理程序时,执行流程永远不会到达reducer函数!

class App extends React.Component {
  constructor(props) {
    super(props);
    if (this.props.appState) {
      this.state = { name: this.props.appState.name };
    }
    else {
      this.state = { name: "Unknown" };
    }
    this.nameChanged = this.nameChanged.bind(this);
    this.sendAction = this.sendAction.bind(this);
  }

  nameChanged(event) {
    this.setState({ name: event.target.value });
  }

  sendAction(event) {
    this.props.saveName(this.state.name);
  }

  render() {
    return (
      <pre>
        <h1>Hello, {this.state.name}!</h1>
        <input type="text" value={this.state.name} onChange={this.nameChanged} />
        <input type="button" value="Click me!" onClick={this.sendAction} />
      </pre>
    );
  }
}

const appReducer = (state = { appState: { name: "World!" } }, action) => {
  debugger;
  switch (action.type) {
    case "SAVE_NAME":
      return Object.assign({}, state, { name: action.name });

    default:
      return state;
  }
};

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);

const combinedReducers = Redux.combineReducers({
  appReducer
});

const store = Redux.createStore(combinedReducers);

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <AppContainer />
  </ReactRedux.Provider>,
  document.getElementsByTagName('main')[0]
);

1 个答案:

答案 0 :(得分:3)

由于您的reducer被称为:appReducer,您需要访问appStateappReducer.appState的{​​{1}}属性,如此

mapStateToProps

对于你的第二个问题,你可以做

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appReducer.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);

或者像这样定义。

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    saveName: (name) => {
      dispatch({ type: "SAVE_NAME", name })
    }
  }
}

然后在连接

const actionCreators = {
    saveName: (name) => {
       return { type: "SAVE_NAME", name }
     },
}
const mapDispatchToProps = (dispatch, ownProps) => {
  return bindActionCreators(actionCreators, dispatch);
}