React + Redux:全局状态未被提供给组件的原因

时间:2017-12-06 19:25:21

标签: reactjs redux

请考虑以下代码。它应该像这样工作;键击应该更新本地状态,单击按钮后,应更新全局状态。组件本身也负责显示全局状态。

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

  nameChanged(event) {
    this.setState(Object.assign({}, this.state, { localName: event.target.value }));
  }

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

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

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

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

    default:
      return state;
  }
};

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

const store = Redux.createStore(combinedReducers);

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

现在,本地状态已正确更新。但是当我单击按钮时,即使创建并发送了操作,但我没有在UI中看到具有新值的全局状态。我不确定全局状态是否未更新或组件未正确通知。

1 个答案:

答案 0 :(得分:0)

<h1>Hello, {this.state.name}!</h1>更改为:

<h1>Hello, {this.props.appState.name}!</h1>

您不必在本地设置状态,Redux会在商店状态更改时通过连接为您更新道具。您需要进行的另一项更改是在您的减速机中。您当前的状态是非常深层嵌套的,并且在您发送操作时,您没有按照您的预期进行操作。这是更新版本:

case "SAVE_NAME": return { ...state, appState: { ...state.appState, name: action.name } }

这是CodePen Link

中的工作版本