我已根据 doc redux 样板正确设置。
我有一个包含各种 Action 文件的文件夹,其中包含 Action 。
在这个文件夹中,我创建了一个 index.js
我正在导出所有这些文件。我将其导入为命名导出。
当我控制台登录功能本身时它就在那里,但是当我控制台注销时this.props
它不存在。
我试图控制台注销类外的函数 undefined
.
如果我直接从文件中导入操作,它在它的工作原理中定义。
Action /formActions.js
export const formInput = (key, val) => (
{
type: FORM_INPUT,
payload: { key, val }
}
);
Action /index.js
export * from './formActions';
FormComp.js
import { formInput } from './actions'; // <-- this.props.formInput = undefined
或者
import { formInput } from './actions/formActions'; // <-- this.props.formInput = func
连接:
class InputField extends Component { ... }
const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);
export { FormComp };
编辑1:如果我在里面
componentWillMount()
console.log(formInput) //without this.props
在那。edit2(解决方案?):
我能够使用
bindActionCreators
将 Action 映射到 Prop .我怎么不明白为什么我需要使用 bindActionCreators
以及为什么我不能直接导出连接,将操作作为第二个参数。const FormComp = connect(
({ forms }) => ({ forms }),
dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);
最佳答案
原因this.props.formInput
未定义但 formInput
定义是因为redux connect没有正确设置函数formInput
针对变量(属性)formInput
在组件 Prop 中。
formInput
是你要导入的函数,this.props.formInput
是应该“指向”您导入的函数的属性。 尝试(为了清楚起见,我已经分开了)
function mapStateToProps(state) {
return {
forms: state.forms
}
}
function mapDispatchToProps(dispatch) {
return {
formInput: (key, val) => dispatch(formInput(key val))
};
}
export connect(
mapStateToProps,
mapDispatchToProps
)(InputField);
然后在您调用的代码中的任何位置
this.props.formInput(key, val);
这将通过 Prop 调用 Action ,因此将调度。适本地
关于javascript - Redux 操作不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286294/