[英]How to watch state variables in redux-toolkit?
Since RTK uses immer internally, the state obtained in the reducer is the draft state of Immer.由于RTK内部使用了immer ,所以在reducer中得到的状态就是Immer的draft状态。 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.
如果想以JS纯对象的形式获取状态,需要使用Immer提供的current方法。
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见 RTK其他出口#current
The
current
function from theimmer
library, which takes a snapshot of the current state of a draft and finalizes it (but without freezing).来自
immer
库的current
函数,它获取草稿当前状态的快照并完成它(但不会冻结)。 Current is a great utility to print the current state during debugging, and the output ofcurrent
can also be safely leaked outside the producer.Current 是在调试过程中打印当前状态的一个很好的工具,并且
current
的输出也可以安全地泄漏到生产者之外。
Also, see Logging Draft State Values另请参阅记录草稿状态值
It's very common for a developer to call
console.log(state)
during the development process.开发者在开发过程中调用
console.log(state)
是很常见的。 However, browsers display Proxies in a format that is hard to read, which can make console logging of Immer-based state difficult.但是,浏览器以难以阅读的格式显示代理,这可能会使基于 Immer 的状态的控制台日志记录变得困难。
When using either createSlice
or createReducer
, you may use the current utility that we re-export from the immer
library.使用
createSlice
或createReducer
,您可以使用我们从immer
库重新导出的当前实用程序。 This utility creates a separate plain copy of the current Immer Draft
state value, which can then be logged for viewing as normal.此实用程序会创建当前 Immer
Draft
状态值的单独普通副本,然后可以将其记录下来以供正常查看。
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:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.