gpt4 book ai didi

reactjs - 在两个 reducer 之间共享状态

转载 作者:行者123 更新时间:2023-12-04 15:59:13 25 4
gpt4 key购买 nike

我有两个 reducer,第一个获取数据,第二个用于根据对原始数据的更改过滤数据。我读过使用 combineReducers 不是一个选项。

我的 postReducer

import {FETCH_POST} from '../actions/types';

const initialState = {
items: [],
item: {}
};

export default function(state = initialState, action){
switch (action.type){
case FETCH_POST:
return Object.assign({}, state, {items: action.payload});
default:
return state;
}

}

我的pinReducer

import {PIN_POST} from '../actions/types';

const initialState = {
items: [],
item: {}
};

export default function(state = initialState, action){
switch (action.type){
case PIN_POST:
console.log(state.items);
const item = state.items.map(value => value.data.id === action.id ?
{data: Object.assign({}, value.data, {pinned: action.val})} : value
);
//console.log(item);
return Object.assign({}, state, {items: item });
default:
return state;
}

}

主要

import {combineReducers} from 'redux';
import postReducer from './postReducer';
import pinReducer from './pinReducer';

export default combineReducers({
post: postReducer,
pin: pinReducer
});

我如何在两个 reducer 之间共享状态,因为 pinReducer 中的 state.items 是空的

最佳答案

你不应该有一个 reducer 的状态是在其他 reducer 的基础上派生的。你需要的是一个选择器(更有效的是 memoizedSelector),你可以使用 reselect library

我的 postReducer

import {FETCH_POST} from '../actions/types';

const initialState = {
items: [],
item: {}
};

export default function(state = initialState, action){
switch (action.type){
case FETCH_POST:
return Object.assign({}, state, {items: action.payload});
default:
return state;
}

}

主要

import {combineReducers} from 'redux';
import postReducer from './postReducer';

export default combineReducers({
post: postReducer,
});

然后在你想使用pinItem的地方,你可以在mapStateToProps中做到这一点

getPinItem = (state, props) => {
const item = state.items.map(value => value.data.id === action.id ?
{data: Object.assign({}, value.data, {pinned: action.val})} : value
);
return item;
}

const mapStateToProps = (state, props) => {
const pinItem = getPinItem(state, props);
return {
pinItem
}
}

关于reactjs - 在两个 reducer 之间共享状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50941919/

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