繁体   English   中英

React + Redux:为什么不向组件提供全局状态

[英]React + Redux: why the global state is not fed to the component

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

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中也看不到带有新值的全局状态。 我不确定全局状态是否未更新或未正确通知组件。

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

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

您不必在本地设置状态,当商店状态更改时,Redux会通过connect为您更新道具。 您需要进行的另一项更改是在减速器中。 您的当前状态非常嵌套,不会在分派操作时返回您期望的状态。 这是更新的版本:

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

这是CodePen Link中的工作版本

暂无
暂无

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

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