reducers: { // 同步 setSampleState: (state, action) => { console.log('state.value1',JSON.stringify(state.value)); console.log('action.payload',JSON.stringify(action.payload)); state.value = Object.assign(state.value, action.payload); console.log('state.value2',JSON.stringify(state.value)); }, },这样设置后,点击查询按钮后,每次state.value都会被清空是怎么回事?
时间: 2024-03-03 13:51:58 浏览: 16
根据你提供的代码,我看到在 `setSampleState` reducer 中,`state.value` 被更新为 `Object.assign(state.value, action.payload)`,这里使用了 `Object.assign` 方法,这个方法会修改第一个参数的值并返回修改后的对象,因此 `state.value` 的值被修改了。然而,`state` 是 Redux 中的状态对象,根据 Redux 的设计原则,状态对象是不允许被直接修改的,因为这会导致 Redux 的时间旅行和状态的可预测性失效。因此,你需要返回一个新的状态对象,而不是修改原来的状态对象。正确的写法应该是使用 `Object.assign` 方法返回一个新的对象,例如:
```
reducers: {
setSampleState: (state, action) => {
return Object.assign({}, state, {
value: Object.assign({}, state.value, action.payload)
});
},
},
```
这样每次更新状态时,都会返回一个新的状态对象,避免了直接修改原状态对象的问题。
相关问题
redux-toolkit中,如何将state.transactions属性的旧对象与新对象合并
在Redux-Toolkit中,可以使用Immer库轻松地实现对象的合并。您可以使用`createSlice`函数的`reducers`字段来定义一个reducer,然后使用Immer库中的`produce`函数来修改状态。以下是一个示例代码:
```javascript
import { createSlice } from '@reduxjs/toolkit';
import produce from 'immer';
const transactionsSlice = createSlice({
name: 'transactions',
initialState: {
transactions: [],
},
reducers: {
mergeTransactions: (state, action) => {
const { oldTransaction, newTransaction } = action.payload;
state.transactions = produce(state.transactions, draftState => {
const oldIndex = draftState.findIndex(t => t.id === oldTransaction.id);
if (oldIndex !== -1) {
draftState[oldIndex] = { ...oldTransaction, ...newTransaction };
}
});
},
},
});
export const { mergeTransactions } = transactionsSlice.actions;
export default transactionsSlice.reducer;
```
在上面的代码中,我们定义了一个名为`mergeTransactions`的reducer,它接受一个包含旧事务和新事务的payload。我们使用Immer库中的`produce`函数来修改`state.transactions`数组,并使用`Array.findIndex`方法找到旧事务的索引。如果找到了旧事务,我们使用对象展开语法将旧事务与新事务合并,并将其设置为数组中的新对象。
您可以将这个reducer与其他reducer一起使用,以便在应用程序中对状态进行更改。例如,您可以在组件中调用`dispatch(mergeTransactions({ oldTransaction, newTransaction }))`来触发此reducer并合并旧对象和新对象。
set hive.exec.reducers .max=<number>
The configuration parameter `hive.exec.reducers.max` is used to set the maximum number of reducers that can be used by a single Hive job. This parameter is used to limit the number of reducers for a particular job in order to prevent the job from consuming too many resources and causing performance issues.
To set this parameter, you need to use the following syntax:
```
set hive.exec.reducers.max=<number>;
```
where `<number>` is the maximum number of reducers that can be used by a Hive job. For example, if you want to set the maximum number of reducers to 10, you can use the following command:
```
set hive.exec.reducers.max=10;
```
Note that this parameter is only used when the number of reducers is not explicitly set for a particular job. If the number of reducers is set explicitly, then this parameter is ignored.