我正在创建一个聊天室应用,此刻我只是在降低本地功能。我创建了一个测试对象来保存聊天室数据,包括消息。现在,我有一个用于聊天的文本输入字段,但似乎无法在我的聊天室对象中访问我的消息以将新消息推送到其中。当我console.log state.messages时,我似乎得到了这个奇怪的代理对象,而不是消息数组。有人知道为什么是这样吗?这是我的代码:
JSX:
<InputGroup className="mb-3">
<FormControl aria-describedby="basic-addon1" className="chat-insert"/>
<InputGroup.Append>
<Button variant="outline-secondary" onClick={() => {
dispatch(addChat(document.querySelector('.chat-insert').value));
document.querySelector('.chat-insert').value = '';
}}>Send</Button>
</InputGroup.Append>
</InputGroup>
数据对象:
let chatData = [
{
name: "General Chatroom",
private: false,
passcode: null,
currentUsers: [],
messages: [
{
avatar: "#",
username: 'Chatter[bot]',
message: `Welcome to Chatter[box]! This is the beginning of this chatroom's history!`
},
]
}
]
export default chatData
减速器:
import { createSlice } from '@reduxjs/toolkit'
import chatData from '../../components/chatData'
export const chatSlice = createSlice({
name: 'chat',
initialState: chatData[0],
reducers: {
addChat: (state, action) => {
console.log(chatData[0])
state.messages.push({
avatar: "#",
username: "",
message: action.payload
})
console.log(state.messages)
},
},
});
export const { addChat } = chatSlice.actions
export const selectChat = state => state.messages
export default chatSlice.reducer
答案 0 :(得分:2)
Redux Toolkit中的createSlice
函数使用Immer库来编写直接修改状态的reducer。减速器中的state
对象是当前状态的“草稿状态”代理。
要快照并打印“草稿状态”,请使用Redux Toolkit从Immer重新导出的current
函数。这是来自Logging Draft State Values的示例:
import { createSlice, current } from '@reduxjs/toolkit'
const slice = createSlice({
name: 'todos',
initialState: [{ id: 1, title: 'Example todo' }],
reducers: {
addTodo: (state, action) => {
console.log('before', current(state))
state.push(action.payload)
console.log('after', current(state))
},
},
})