【问题标题】:how to call ajax in react using `redux-thunk`?如何使用“redux-thunk”调用 ajax?
【发布时间】:2017-05-11 23:14:26
【问题描述】:

我正在尝试使用 redux-thunkaxios 调用 ajax。我想从 json 文件中获取数据

简单的方法(按钮点击调用这样的)

 axios.get('data.json').then((data)=>{
      console.log(data);
    })

但我想使用redux-thunk。换句话说,我需要订阅组件,该组件将使用thunk进行调度

我们可以在这里使用 thunk 吗? 这是我的代码 https://plnkr.co/edit/bcGI7cHjWVtlaMBil3kj?p=preview

const thunk = ReduxThunk.default;
const abc= (state={},action) => {
  console.log('in redux', action.type)
  switch(action.type){
    case 'GET_DATA':
      return dispatch =>{
        return axios.get('data.json');
      };

      default :
      return state;
  }
}
const {createStore,bindActionCreators ,applyMiddleware } =Redux;
const {Provider,connect} =ReactRedux;

const store = createStore(abc,
applyMiddleware(thunk)
);

class First extends React.Component {
  constructor (props){
    super(props);

  }

  getDate(){
    this.props.getData();
    // axios.get('data.json').then((data)=>{
    //   console.log(data);
    // })
  }
  render(){
    return (
    <div>
      <button onClick={this.getDate.bind(this)}>GET DATA</button>

    </div>
    )
  }
} 

const actions = {
    getData: () => {
        return {
            type: 'GET_DATA',
        }
    }
};

const AppContainer = connect(
    function mapStateToProps(state) {
        return {
            digit: state
        };
    },
    function mapDispatchToProps(dispatch) {
        return bindActionCreators(actions, dispatch);
    }
)(First);
ReactDOM.render(
   <Provider store={store}>
    <AppContainer/>
  </Provider>
  ,document.getElementById('root'))

【问题讨论】:

    标签: reactjs react-router react-redux redux-thunk axios


    【解决方案1】:

    egghead.io 上有一个关于这个的很好的教程……你可能想看看。 https://egghead.io/lessons/javascript-redux-dispatching-actions-asynchronously-with-thunks

    【讨论】:

      【解决方案2】:

      我这里以axios为例调用api,你也可以使用fetchsuperagent。你可以试试类似的。

      AXIOS

       axios.get('//url')
        .then(function (response) {
          //dispatch action
        })
        .catch(function (error) {
          // throw error
        });
      

      这就是 API 调用,现在进入状态。在 redux 中,有一种状态可以处理您的应用程序。我建议您应该阅读可以找到 here 的 redux 基础知识。因此,一旦您的 api 调用成功,您需要使用数据更新您的状态。

      获取数据的操作

       function fetchData(){
          return(dispatch,getState) =>{ //using redux-thunk here... do check it out 
              const url = '//you url'
              fetch(url)
              .then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array
              .catch( error) => {//throw error}
          }
        }
      

      更新状态的动作

         function receiveData(data) {
            return{
              type: 'RECEIVE_DATA',
              data
           }
         }
      

      减速器

         function app(state = {},action) {
            switch(action.types){
                case 'RECEIVE_DATA':
                       Object.assign({},...state,{
                         action.data 
                           }
                        }) 
                default:
                   return state
            }
         }
      

      【讨论】:

        猜你喜欢
        • 2021-08-11
        • 2021-12-11
        • 2016-08-07
        • 2018-03-19
        • 2021-02-27
        • 2018-07-11
        • 2021-08-24
        • 1970-01-01
        • 2020-12-14
        相关资源
        最近更新 更多