我在redux中尝试更改复选框状态。除最后一部分外,一切都正确设置。我尝试发送一个" false"或"真"并决定行动什么,但我得到这个错误
Uncaught TypeError: Cannot read property 'payload' of undefined
这是我的代码
export function isChecked(isCheck) {
if(isCheck == false){
return{
type: "IS_TRUE",
isCheck
}
} else if (isCheck == true){
return{
type: "IS_FALSE",
isCheck
}
}
}
如果我把其他问题放好,那么它可以正常工作但是第二次它没有改变
答案 0 :(得分:2)
您正在以错误的方式使用redux,这是复选框的示例:
// action
export const SET_CHECKBOX_VALUE = 'SET_CHECKBOX_VALUE ';
export function setChecked(checked) {
return {
type: SET_CHECKBOX_VALUE,
checked
}
}
// filter/Reducer
import { SET_CHECKBOX_VALUE } from '..your action file here';
const initialCheckboxState = { isChecked: false };
export default function checkBoxFilter(state, action) {
switch (action.type) {
case SET_CHECKBOX_VALUE :
return { checked: action.checked}
default:
return initialCheckboxState;
}
}
// component
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as checkBoxActions from '..your action file here';
class MyComponent extends Component {
static propTypes = {
isChecked: React.PropTypes.bool.isRequired,
setChecked: React.PropTypes.func.isRequired
};
render() {
return (
<div onClick={() => { this.props.setChecked(!this.props.isChecked) }>
{this.props.isChecked}
</div>
);
}
}
function mapStateToProps(state) {
return {
isChecked: state.checkBoxFilter.checked
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(checkBoxActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);