ReactJs useState.map()不是函数 [英] ReactJs useState .map() is not a function

查看:46
本文介绍了ReactJs useState.map()不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解useStateuseEffect挂钩在ReactJ中是如何工作的。

我收到错误消息

.map()不是函数

在尝试显示表中的数据时。

const [posts, setPosts] = useState([]);

useEffect(() => {
    const alarmService = new AlarmService();
    const response = alarmService.getData();
    setPosts(response)
}, [])

return (
    <table className="table">
        <tbody>
        {posts.map(data => (
            <tr key={data.id}>
                <td>
                    <div className="row">
                        {data.name}
                    </div>
                </td>
                <td className="custom" >
                    <button
                        className="btn btn-danger btn-sm"
                        onClick={() => this.handleDelete(data)}
                    >
                        Delete
                    </button>
                </td>
            </tr>
        ))}
        </tbody>
    </table>
);

我假设问题出在我的useEffect中,因为我不确定如何处理响应。

已解决

我研究了以下示例: https://www.robinwieruch.de/react-hooks-fetch-data/

诀窍是在useEffect中创建一个异步函数。如下所示:

useEffect(() => {
    async function test() {
       const alarmService = new AlarmService();
       const response = await alarmService.getData();
       console.log(response);
       setPosts(response)
    }
    test();
}, []);

感谢所有花时间回应和帮助的人!

推荐答案

我认为这里的问题是alarmService.getData是异步的,您没有正确处理它。这就是为什么您将承诺挂起,并且您不能在帖子上映射。

useEffect(() => {
    const alarmService = new AlarmService();
    alarmService.getData().then(response => response.json()).then(data =>setPosts(data))    

}, []) 

这应该可以解决您的问题。

这篇关于ReactJs useState.map()不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆