我正在创建一个聊天室应用程序,目前我只是在获取本地功能。我已经创建了一个测试对象来保存聊天室数据,包括消息。现在,我有一个用于聊天的文本输入字段,但我似乎无法访问聊天室对象中的消息以将新消息推送到其中。当我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控制台日志:

发布于 2020-10-20 04:51:54
Redux Toolkit中的createSlice函数使用Immer库来允许编写直接修改状态的reducers。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))
},
},
})https://stackoverflow.com/questions/64434418
复制相似问题