提前谢谢.

我需要在状态数组中添加一个项,我发现我们不需要进行状态变异.如何使用prevState设置状态.

const [messages, setMessages] = React.useState(
        [
            {
                _id: 12,
                createdAt: new Date(),
                text: 'All good',
                user: {
                    _id: 1,
                    name: 'Sian Pol',
                }
            },
            {
                _id: 21,
                createdAt: "2019-11-10 22:21",
                text: 'Hello user',
                user: {
                    _id: 2,
                    name: 'User New'
                }
            }]
    )

如何调用set State来附加这个Statearray.

像这样的?

setMessages(previousState => ({...stat

谁能帮我弄到上面的代码吗.

推荐答案

在列表末尾插入新元素的步骤

const addMessage = (newMessage) => setMessages(state => [...state, newMessage])

在列表开头插入新元素的步骤

const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])

React-native相关问答推荐

在原生react 中更改图像源URI时闪烁

任务:react-native-async-storage_async-storage:generateDebugRFile FAILED

在 ReactNative 中调用 RCTDeviceEventEmitter.emit 时出错

如何在react-native 中设置视图的自动高度

如何在 Recompose 中使用 withHandlers 将 refs 添加到功能组件并在 ScrollView 上调用 ScrollTo?

如何解决Readonly<{}> 类型上不存在属性 navigation&

使用 React-Native 将 content:// URI 转换为 Android 的实际路径

React-navigation:增加底部标签导航的高度?

react-native android中出现此问题Cannot convert argument of type class org.json.JSONArray的原因是什么?

React Native Maps:标记图像不显示在 react-native-maps 中使用自定义标记

从数据源添加/删除列表视图项时为它们设置动画

react-native run-android 构建错误':app:generateDebugBuildConfig'

React-native:图像未显示在 android 设备中,但在模拟器中完美显示

react-native如何禁用android开发模式

如何更改键盘上的 return按钮?

如何在react-native中绘制虚线边框样式

如何从 React-Native 中的另一个类调用函数?

React本机IOS,当TextInput获得焦点时,按钮按下不注册

React Native:如何动态更改

在 React Native 中,两个等宽的按钮水平填充屏幕