栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

React-在其中添加新元素后刷新数据列表的最佳实践是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React-在其中添加新元素后刷新数据列表的最佳实践是什么?

对于新手来说,这是最具挑战性的部分之一

ReactJS
。您不应该在每个级别上创建有状态组件。

选择州的共同所有者。在您的情况下

Items
,没有上级
App
组件的数据,组件本身无法更改其状态,因此没有理由将状态保持在该位置。

基本上,您应该将

items
数组和
isLoading
标志保留在
App
组件中,然后将其
Items
作为道具简单地传递给。

然后,您可以通过在后端添加新项后重新获取数据来更新列表,也可以将其添加到列表中。

另外,您应该

App
在每次输入更改时更新父级的状态。

有两种方法:

  1. 您可以使其保持

    NewItemForm
    状态,然后将onSubmit作为函数prop传递到父事件处理程序中。

  2. 只是使其不可控制,根本不要保持它的状态,父级将继承此参数

    event.target.value
    。(现在)。

在两种情况下,它都不会每次都重新呈现您的列表。因此,您应该省略

handleInputChange
from
App
组件。

例如: App.js

constructor(props) {    super(props);    // Initial state    this.state = {        items: [],        isLoading: false,    }}handleSubmit(e){     e.preventDefault();    const { value } = e.target;    this.setState({ isLoading: true });    axios.post('/api/v1/items', {        item: value      })      .then(response => {        // there are several ways - choose ONE of them        // 1. If server returns you the created item        // you can just add this item into the list        this.setState(prevState => {    return {        items: [...prevState.items, response.data],        isLoading: false,    }        });        // 2. But if there are any users who can make changing simultaneously with you         // (if not - just imagine it :) ) - it's better to make re-fetch data from server        axios.get('/api/v1/items') .then(response => {     this.setState(prevState => ({ items: response.data, isLoading: false });  }) .catch(err => { console.log('Something bad is happened:', err) });}

最后,只需将数据传递到您的

Items
组件中即可。

render() {    const { items, isLoading } = this.state;    return (      ...      <Items items={items} isLoading={isLoading} />      ...    )}

如果您尚未阅读本文,建议您阅读这篇文章-https: //reactjs.org/docs/thinking-in-
react.html

希望能帮助到你。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427284.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号