该应用程序仅应显示“ Hello”,当您单击它时,切换到“ Goodbye”,但不会呈现“ Hello”。我已经设置了默认状态,连接了所有东西,等等。但是我无法弄清我所缺少的东西。

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { connect } from 'react-redux';

import "./styles.css";

const switcheroo = () => {
  return {
    type: 'SWITCH'
  };
};

const switchReducer = (state = {value: 'Hello'}, action) => {
  switch (action.type) {
    case 'SWITCH':
      return { ...state, value: 'Goodbye' };

    default:
      return state;
  }
}

class ClickMachine extends React.Component {
  render() {
    const { value, switcheroo } = this.props;
    return(
      <div >
        <p onClick={switcheroo}>{value}</p>
      </div>
    )
  }
};

const mapStateToProps = (state) => ({
  value: state.value,
});

const mapDispatchToProps = (dispatch) => ({
  switcheroo: () => dispatch(switcheroo()),
});

connect(mapStateToProps, mapDispatchToProps)(ClickMachine);


const store = createStore(switchReducer);

class AppWrapper extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ClickMachine />
      </Provider>
    );
  };
};

const rootElement = document.getElementById("root");
render(<AppWrapper />, rootElement);


我的CodeSandbox在这里:https://codesandbox.io/s/k29r3928z7,我具有以下依赖关系:


反应
反应域
react-redux
还原

最佳答案

这是因为您尚未将连接功能分配给组件,否则将无法将Redux与ClickMachine组件相关联
只需更改此行,它将起作用

 ClickMachine = connect(mapStateToProps, mapDispatchToProps)(ClickMachine);


沙盒链接https://codesandbox.io/s/4x2pr03489

10-08 12:25