我是React和Redux的新手,我试图更改一个下拉字段值onChange,但是当我选择该值时,我得到了。即使我花了几天时间研究以找到更好的解决方案以及如何重写Action函数,但看起来我仍在遵循Redux https://redux.js.org/basics的基础知识,但是在文档中查找的内容几乎是相同的。
TypeError:无法读取未定义的属性'setStatus'
我的index.js
// @flow
import React from 'react';
import Select from 'react-select'
import {connect} from 'react-redux'
import {
setStatus,
} from '../../actions'
type Props = {
status: { value: ?string, label: ?string },
setStatus: Function,
}
type State = {}
// Select Invoice Type
const statusOptions = [
{value: 'paid', label: 'Paid'},
{value: 'due', label: 'Due'},
{value: 'overdue', label: 'Overdue'},
{value: 'onhold', label: 'On Hold'}
];
class Dashboard extends React.Component<Props, State> {
state: State;
constructor(props: Props) {
super(props);
this.state = {}
}
handleChangeStatus(value: { value: ?string, label: ?string }) {
console.log(value)
if (value)
this.props.setStatus(value);
else
this.props.setStatus({value: 'paid', label: 'Paid'});
};
render() {
return (
<div>
{/* Select Invoice Status */}
<Select
name="status"
value={this.props.status}
options={statusOptions}
searchable={false}
onChange={this.handleChangeStatus}
/>
</div>
)
}
}
function mapStateToProps(state, ownProps) {
return {
status: state.status,
}
}
function mapDispatchToProps(dispatch) {
return {
setStatus: (statusObj) => dispatch(setStatus(statusObj)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
我的`/action/index.js /
// @flow
import {
SET_INVOICE_STATUS,
} from '../constants';
export type Action = {
status?: Object,
}
export function setStatus(status: Object): Action {
return {
type: SET_INVOICE_STATUS,
status
}
}
我的/constant/index.js
// @flow
// Dashboard Implementation
export const SET_INVOICE_STATUS: string = "SET_INVOICE_STATUS";
最后是我的reducer/index.js
// @flow
import {SET_INVOICE_STATUS} from "../constants";
import type {Action} from "../actions";
type State = Object;
export default function statusReducer(state: State = {value: 'paid', label: 'Paid'}, action: Action) {
if (action.type === SET_INVOICE_STATUS) {
return action.status;
}
return state;
}
2018年9月2日更新
因此,在学习了可用于我的项目的babel和插件一周之后,我找到了一种解决方案,可将插件安装到babel中,以帮助创建错误函数,例如handleChange = (event) => {}
,其名为{{1} },位于此处https://babeljs.io/docs/en/babel-plugin-transform-class-properties/。感谢Bhojendra Rauniyar提供的绑定帮助。
答案 0 :(得分:4)
当您这样做:
this.props.setStatus(value);
this
未定义。因为,您的方法不受限制。因此,您需要绑定this
。有不同的方法,您可以尝试在构造函数内部绑定this
:
this.handleChangeStatus = this.handleChangeStatus.bind(this)
答案 1 :(得分:0)
就像@Bhojendra所说,您可以通过以下两种方式之一进行操作(都需要绑定handleChangeStatus
函数。首先是使用箭头函数:
handleChangeStatus = (value: { value: ?string, label: ?string }) => { //binds with arrow func
console.log(value)
if (value)
this.props.setStatus(value);
else
this.props.setStatus({value: 'paid', label: 'Paid'});
};
或者两个,在构造函数处绑定:
constructor(props: Props) {
super(props);
this.state = {}
this.handleChangeStatus = this.handleChangeStatus.bind(this) // binding this to your function
}
您无需同时执行两项操作,而只需执行一项操作。箭头功能最简单,但两者均可。