javascript - 如何在react-native中使用thunk?

标签 javascript reactjs redux react-redux redux-thunk

我正在学习 redux,

我只是想模拟从服务器获取数据,所以我使用setTimeout()来处理它,

但是有一个错误

Error: Actions must be plain objects. Use custom middleware for async actions.

虽然我安装了 redux-thunk 但并没有解决它!

这是代码

./actions/userActions.js

const setName = name => {
  return dispatch => {
    setTimeout(() => {
      dispatch({
        type: 'SET_NAME',
        payload: name,
      });
    }, 2000);
  };
};

const setAge = age => {
  return {
    type: 'SET_AGE',
    payload: age,
  };
};

export {setName, setAge};

./reducers/userReducers.js

const userReducer = (
  state = {
    name: 'Max',
    age: 27,
  },
  action,
) => {
  switch (action.type) {
    case 'SET_NAME':
      state = {
        ...state,
        name: action.payload,
      };
      break;
    case 'SET_AGE':
      state = {
        ...state,
        age: action.payload,
      };
      break;
  }
  return state;
};

export default userReducer;

./store.js

import {applyMiddleware, combineReducers, compose, createStore} from 'redux';
import thunk from 'redux-thunk';
import mathReducer from '../reducers/mathReducer';
import userReducer from '../reducers/userReducer';

const store = createStore(
  combineReducers(
    {math: mathReducer, user: userReducer},
    // applyMiddleware(thunk) not work :]
    compose(applyMiddleware(thunk)), //same :]
  ),
);

export default store;

App.js

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Main changeUsername={() => this.props.setName('Oliver')} />
        <User username={this.props.user.name} />
      </View>
    );
  }
}



const mapStateToProps = state => {
  return {
    user: state.user, //user is a key == userReducer
    math: state.math,
  };
};

const mapDispatchToProps = dispatch => {
  // to excute the actions we want to invok
  return {
    setName: name => {
      dispatch(setName(name));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

最佳答案

您正在传递applyMiddleware(thunk)作为combineReducers参数,它应该作为createStore第二个参数传递。

const store = createStore(
  combineReducers({math: mathReducer, user: userReducer}),
  applyMiddleware(thunk)
);

关于javascript - 如何在react-native中使用thunk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129948/

相关文章:

javascript - window.location 重定向到 IE11 和 mozilla 中的主页

android - react native 弹性框不使用所有可用空间

reactjs - (react-native-svg错误) "Tried to register two views with the same name RNSVGRect"

javascript - 使用map函数在react中渲染表格主体

javascript - 如何将 dispatch 传递到 prop 之类的组件中?

javascript - 类型错误 : Cannot read property 'carts' of null

reactjs - 如何使用 React Redux Hooks 加载 Spinner

javascript - Chrome 扩展程序可更改特定网站的文本样式

javascript - AngularJS 组件需要 : componentOne OR componentTwo

javascript - 从 xsd 获取 html 表单