gpt4 book ai didi

javascript - Redux 中的异步请求

转载 作者:行者123 更新时间:2023-11-30 21:21:36 25 4
gpt4 key购买 nike

这是我的商店:

import {createStore, applyMiddleware} from 'redux';
import reducerFoo from './reducers/reducer';
import thunkMiddleware from 'redux-thunk';

export default function configureStore() {
return createStore(
reducerFoo,
applyMiddleware(thunkMiddleware)
);
}

Action :

import * as types from './actionTypes';    
import axios from 'axios';

export const selectTag = function(tag) {

fetchQuestions(tag);

return {
type: types.SELECT_TAG,
selectedTag: tag
}
};

export const receiveQuestions = (json) => ({
type: types.RECEIVE_QUESTIONS,
questions: json
});

export const fetchQuestions = tag => {

console.log(tag);

let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
console.log(url);

return function(dispatch) {
return axios.get(url).then((response) =>
dispatch(receiveQuestions(response))
);
};
};

reducer :

import * as types from '../actions/actionTypes';
import { fetchQuestions } from '../actions/actions';

const initialState = {
questions: [],
showTagPanel: true,
selectedTag: '...',
tags: ['one', 'two', 'three']
};


export default function reducerFoo(state = initialState, action) {

switch(action.type) {

case types.SHOW_TAG_PANEL:

return Object.assign({}, state, {
showTagPanel: true
});

case types.SELECT_TAG:

return Object.assign({}, state, {
showTagPanel: false,
selectedTag: action.selectedTag
});

case types.RECEIVE_QUESTIONS:

console.log('get it');
return state;

default:
return state;
}
}

我可以在控制台中看到 urltag:

export const fetchQuestions = tag => {

console.log(tag);

let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
console.log(url);

但是 RECEIVE_QUESTIONS 操作不起作用:

case types.RECEIVE_QUESTIONS:
console.log('get it');
break;

为什么以及如何解决?

更新:但如果我从 index.js 调用它,它会起作用:

const store = configureStore();
store.dispatch(fetchQuestions('...'));

更新 2: 我认为在 selectTag() 中我需要使用

dispatch(fetchQuestions(tag));

代替

fetchQuestions(tag);

但我不知道如何在此处获取 dispatch()

最佳答案

在您的 fetchQuestions 函数中,您有:

return function(dispatch) {
return axios.get(url).then((response) =>
dispatch(receiveQuestions(response))
);
};

但是,您在 selectTag 函数中调用该函数的地方:fetchQuestions(tag); 正在返回

function(dispatch) {
return axios.get(url).then((response) =>
dispatch(receiveQuestions(response))
);
};

但它永远不会在其他任何地方被调用。因此,您可以做的一件事是不要在 fetchQuestions 中返回该函数,只需调用 axios.get 部分,该部分最终将派发 receiveQuestions get 请求返回后执行操作。

export const fetchQuestions = tag => {

console.log(tag);

let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';
console.log(url);

return axios.get(url).then((response) =>
dispatch(receiveQuestions(response))
);
};

关于javascript - Redux 中的异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com