ReactJs useState.map()不是函数

2022-03-03 reactjs javascript jsx

我试图了解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))    

}, []) 

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

相关文章