动作必须是React/Redux中的普通对象? [英] Actions must be plain Objects in React/Redux?
问题描述
当我通过动作创建者传递数据时,我遇到的问题是Actions must be plain objects
.基本上,我试图通过单击按钮来捕获用户输入,然后基于单击了哪个按钮(视图),将event.target.innerHTML
传递给操作创建者fetchDataAsync(view)
,该操作创建者fetchDataAsync(view)
通过axios进行GET请求,并根据选择的视图进行分派.
the problem I'm running into is Actions must be plain objects
when passing data through my action creators. Basically I'm trying to capture user input through the click of a button, and based on what button (view) is clicked the event.target.innerHTML
is passed to the action creator fetchDataAsync(view)
which then performs a GET request via axios and dispatches based on what view was selected.
不过,我对Redux还是陌生的,我不确定自己在做什么错.我之前看到过在动作创建者内部执行过异步动作...
I'm still new with Redux, though, and I'm unsure of what I'm doing wrong here. I've seen an async action performed inside an action creator before...
与Redux连接的组件:
Component connected with Redux:
class ViewSelector extends Component {
selectView(event) {
this.props.fetchDataAsync(event.target.innerHTML);
}
render() {
return (
<nav>
<button onClick={this.selectView.bind(this)}>VIEW ALL</button>
<button onClick={this.selectView.bind(this)}>VIEW LAST WEEK</button>
<button onClick={this.selectView.bind(this)}>VIEW LAST MONTH</button>
</nav>
);
}
}
function mapStateToProps(state) {
return {
view: state.view
};
}
export default connect(mapStateToProps, actions)(ViewSelector);
用于基于event.target.innerHTML
进行调度的动作创建者:
Action creator for dispatching based on event.target.innerHTML
:
export function fetchDataAsync(view) {
return dispatch => {
dispatch(fetchData());
axios.get(DATA_URL)
.then(res => {
dispatch(fetchDataSuccess(res.data));
if (view == 'VIEW LAST WEEK') {
dispatch(lastWeekData(res.data));
} else if (view == 'VIEW LAST MONTH') {
dispatch(lastMonthData(res.data));
}
}).catch(err => {
dispatch(fetchDataFailure(err));
});
};
}
任何建议都值得赞赏.或者,如果您认为有一种更有效的方法来捕获用户输入并将其传递给动作创建者...我很想听到更多信息!
Any advice is appreciated. Or if you believe there's a more effective way of capturing that user input and passing it to an action creator...I'd be curious to hear more!
推荐答案
您需要安装redux-thunk才能使用异步操作.然后像这样创建您的商店
You need to install redux-thunk to use async action. And then create your store like this
import thunk from 'redux-thunk';
const store = createStore(YOURREDUCER, applyMiddleware(thunk));
这篇关于动作必须是React/Redux中的普通对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!