试图构建一个基本的React Redux点击切换器,但什么都没有显示



应用程序应该只显示"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 dom
  • 反应还原
  • redux

这是因为您没有将连接函数分配给组件,没有连接函数,redux就不会与ClickMachine组件关联只要换一下这条线,就行了

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

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

最新更新