Since RTK uses immer internally, the state obtained in the reducer is the draft state of Immer. If you want to get the state in the form of a JS plain object, you need to use the current method provided by Immer.
This can be very useful for debugging purposes (as those objects won't be Proxy objects and not be logged as such)
See RTK other-exports#current
The
current
function from theimmer
library, which takes a snapshot of the current state of a draft and finalizes it (but without freezing). Current is a great utility to print the current state during debugging, and the output ofcurrent
can also be safely leaked outside the producer.
Also, see Logging Draft State Values
It's very common for a developer to call
console.log(state)
during the development process. However, browsers display Proxies in a format that is hard to read, which can make console logging of Immer-based state difficult.
When using either createSlice
or createReducer
, you may use the current utility that we re-export from the immer
library. This utility creates a separate plain copy of the current Immer Draft
state value, which can then be logged for viewing as normal.
Eg
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/@reduxjs/toolkit@1.6.1/dist/redux-toolkit.umd.js"></script>
</head>
<body>
<script>
window.onload = function () {
const { configureStore, createSlice, current } = window.RTK;
const counterSlice = createSlice({
name: 'user',
initialState: { value: 0 },
reducers: {
increment(state) {
console.log('immer draft state: ', state)
console.log('js object state: ', current(state))
state.value++;
},
},
});
const store = configureStore({ reducer: counterSlice.reducer });
store.dispatch(counterSlice.actions.increment());
}
</script>
</body>
</html>
Output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.