动作必须是 React/Redux 中的普通对象吗? [英] Actions must be plain Objects in React/Redux?

查看:12
本文介绍了动作必须是 React/Redux 中的普通对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是在通过我的动作创建者传递数据时动作必须是普通对象.基本上,我试图通过单击按钮来捕获用户输入,并且根据单击的按钮(视图),将 event.target.innerHTML 传递给action creator 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆