假设其中一个具有以下组成文件HelloForm.jsx
:
import React from 'react';
import {graphql} from 'react-apollo';
import {connect} from 'react-redux';
import {actions, Control, Form} from 'react-redux-form';
import {compose, withProps} from 'recompose';
import query from './HelloForm.gql';
const passThrough = fn => BaseComponent => props => {
fn(props, BaseComponent);
return BaseComponent(props);
};
export const HelloForm = ({onSubmitEventHandler}) =>
<Form
className="my-form"
model="forms.hello"
onSubmit={onSubmitEventHandler}
>
<label htmlFor="name">Name</label>
<Control.text
{...props}
model=".name"
id="name"
/>
<button type="submit">Say Hello</button>
</Form>;
export const enhance = compose(
connect(),
withProps({
onSubmitEventHandler: ({name}) => {
window.alert(`Hello, ${name}`);
},
}),
graphql(query),
passThrough(({data, dispatch, loading}) => {
if (!loading) {
dispatch(actions.load('forms.hello', data));
}
}),
);
export default enhance(HelloForm);
这似乎按预期方式工作,但会收到以下警告:
警告:
setState(...)
:在现有状态转换期间(例如在render
或另一个组件的构造函数中)无法更新。渲染方法应该纯粹是道具和状态的函数;构造函数的副作用是反模式,但可以移至componentWillMount
。但是,React's component documentation建议在
componentDidMount
生命周期事件中分派操作(可以通过recompose.lifecycle
使用功能组件来完成)。但是没有道具提供给componentDidMount
事件处理程序。“异步”向Redux分发操作的正确方法是什么?
最佳答案
解决方案的确是使用recompose.lifecycle
高阶组件。但是,一定不能使用箭头功能。更新的enchance
高阶组件应按以下方式实现:
export const enhance = compose(
connect(),
withProps({
onSubmitEventHandler: ({name}) => {
window.alert(`Hello, ${name}`);
},
}),
graphql(query),
lifecycle({
componentDidMount: function () {
const {dispatch, loading, recipe} = this.props;
if (loading) {
dispatch(actions.load('forms.hello', data));
}
},
}),
);
关于javascript - 如何将数据异步加载到Redux?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46413063/