gpt4 book ai didi

reactjs - 如何使用redux React调用另一个reducer方法

转载 作者:行者123 更新时间:2023-12-03 13:55:35 24 4
gpt4 key购买 nike

Reducer 1 代码如下。我想在成功验证用户身份后调用另一个 reducer 方法。所以它是基于reducer 1的响应,我想调用reducer 2的方法/操作。

const LOGIN = 'redux-example/auth/LOGIN';
const LOGIN_SUCCESS = 'redux-example/auth/LOGIN_SUCCESS';
const LOGIN_FAIL = 'redux-example/auth/LOGIN_FAIL';
import { browserHistory } from 'react-router';
import { apiurl } from '../../Constants';

import {savedata} from '../../redux/modules/new';

export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOGIN:
return {
...state,
loggingIn: true
};
case LOGIN_SUCCESS:
return {
...state,
loggingIn: false,
user: action.result
};
case LOGIN_FAIL:
return {
...state,
loggingIn: false,
user: null,
loginError: action.error
};
default:
return state;
}
}

export function login(page,email,password) {
var querystring = require('querystring');
if(action == undefined) action = null;
var data = querystring.stringify({
email: email,
password: password
});
return {
types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL],
promise: (client) => client.post(apiurl + 'ajax/login', {
data: data
}).then(response => {
//console.log(response);
switch(page){
case 'signin':
if(response.auth == 'true') {
redirectuser(response);
}
break;
default:
break;
}
return response;
})
.catch( error => Promise.reject(error))
};

}

export  function  redirectuser(response) {
console.log('response is as below');
console.log(response);
if(response.action == 'action1'){
savedata();
// here I want call another reducer method save data
}
}

当我从reducer 1调用reducer 2的保存数据操作时,它不起作用。如何从reducer 1分派(dispatch)reducer 2的action。

编辑1:我的中间件代码如下

export default function clientMiddleware(client) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}

const { promise, types, ...rest } = action; // eslint-disable-line no-redeclare
if (!promise) {
return next(action);
}

const [REQUEST, SUCCESS, FAILURE] = types;
next({ ...rest, type: REQUEST });

const actionPromise = promise(client, dispatch);
actionPromise.then(
result => next({ ...rest, result, type: SUCCESS }),
error => next({ ...rest, error, type: FAILURE })
).catch(error => {
next({ ...rest, error, type: FAILURE });
});

return actionPromise;
};
}

最佳答案

在 reducer 内分派(dispatch) Action 并不是一个好的举动。据我了解,您必须同步进行一些更新。一种方法是,一旦更新第一个 reducer ,无论您在何处使用该 reducer ,并在 componentWillReceiveProps 或 componentDidUpdate 内执行类似的操作。注意:在调度之前,您必须导入configurestore并从store创建一个const调度。

componentWillReceiveProps(nextProps)
{
//only if user was not there previously and now user is there
if(!this.props.user && nextProps.user)
{
dispatch({type: SECOND_ACTION, payLoad})
}
}

关于reactjs - 如何使用redux React调用另一个reducer方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41830393/

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