gpt4 book ai didi

javascript - react + redux + axios : actions not sent to reducers

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

我正在构建一个 React+Redux 应用程序。我正在使用 axios 来发出 api 请求。我正在尝试发出三个 api 请求,一个接一个。第一个需要在第二个可以运行之前完成,因为第一个返回一个用户对象,第二个在他们的请求中使用。

我运行 getUser,只有与 getUser 相关的应用程序状态得到更新。但是其他两个 api 没有按应有的方式更新应用程序状态。 getUserScores 和 getCustomerEquations 都不会真正改变状态。从我的 gulp 过程中我知道所有的 API 请求都是成功的。从 console.log 我知道 axios promise 已创建。

因此,由于某些未知原因,我的函数返回的对象没有进入 reducer。这里缺少什么?

感谢您的帮助!

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise'; //this is middleware

import App from './containers/app';
import reducers from './reducers/index';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.getElementById('container'));

Action /索引:

import axios from 'axios';

export function getUser(email) {
let url = 'api/users?user__email=' + email;

axios.get(url)
.then((response) => {
getCustomerEquations(response.data[0].customer);
getUserScores(response.data[0].id);
});

let request = axios.get(url);

return {
type: 'GET_USER',
payload: request
}
}

export function getUserScores(userId) {
let url = '/api/user_scores?user__id=' + userId;


let request = axios.get(url);

return {
type: 'GET_USER_SCORES',
payload: request
};
}

export function getCustomerEquations(customerId) {
let url = '/api/equations?customer__id=' + customerId;
let request = axios.get(url);

return {
type: 'GET_CUSTOMER_EQUATIONS',
payload: request
};
}

reducers/reducer-getUserScores:

import React from 'react';
import { GET_USER_SCORES } from '../actions/index';

export default function(state = ["d"], action = {}) {
switch(action.type) {
case GET_USER_SCORES:
// do not manipulate existing state. create a new one
//ES6 way to write 'return state.concat(action.payload.data);

console.log('userScores in Reducer:', action.payload.data);
return action.payload.data;
default:
console.log('userScores-Reducer: the case didnt match', action.type);

}
return state;
}

最佳答案

您需要返回一个函数而不是一个 Action ,并且仅当您的条件匹配时才分派(dispatch)该 Action 。您可以尝试编写自己的简单中间版本的 middle where,或者您可以使用 thunk https://github.com/gaearon/redux-thunk

关于javascript - react + redux + axios : actions not sent to reducers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435312/

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