繁体   English   中英

如何在 react-native 中使用 thunk?

[英]How to use thunk in react-native?

我正在学习 redux,

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

但它有一个错误

错误:操作必须是普通对象。 使用自定义中间件进行异步操作。

虽然我安装了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;

应用程序.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)
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM