我是第一次尝试 React/Redux/JS。我对在组件中设置状态与让 redux 更新它有点困惑。
我想单击一个按钮将 lightOn 设置为 true 并显示更新的 this.props.lightOn 值。我错过了一些基本的东西,但不确定是什么。
行动:
export const setLight = lightStatus => dispatch => {
const res = lightStatus;
console.log(res); // => true on click
dispatch({ type: SET_LIGHT, payload: res });
};
在组件中, {this.props.onLight} 未定义,所以我没有正确更新状态:
import React, { Component } from 'react';
import { connect } from 'react-redux';
//import * as actions from '../actions';
import { setLight } from '../actions';
import { bindActionCreators } from 'redux';
class Light extends Component {
render() {
return (
<div>
Light Status: {this.props.lightOn}
<button
className="btn"
onClick={() => this.props.setLight(true)}
>
Set Light!
</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
lightOn: state.lightOn
};
}
function mapDispatchToProps(dispatch) {
//whenever selectBook is called the result should be passed to all of our reducers
return bindActionCreators({ setLight: setLight }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Light);
减速器(使用扩展运算符更新):
import { SET_LIGHT } from '../actions/types';
export default function(state = [], action) {
switch (action.type) {
case SET_LIGHT:
return { ...state, lightOn: action.payload };
default:
return state;
}
}