使组件添加新组件的问题

Posted

技术标签:

【中文标题】使组件添加新组件的问题【英文标题】:issue to make a component add a new component 【发布时间】:2020-02-26 18:04:20 【问题描述】:

我正在使用 react js、html 和 css 构建一个餐厅评论网站。我需要让子组件 RestaurantInput 更新兄弟组件 Restaurant 列表。 我创建了通过回调将信息传递给 App 组件(父级)的处理程序,并且当 RestaurantInput 中的输入发生更改时,处理程序会对其进行更新。 App 组件通过 props 将信息传递给 RestaurantList 组件,该组件将在 UI 上呈现新餐厅。 可惜没有新餐厅的渲染图。我不知道我哪里弄错了。有人可以帮忙吗?

我试图在我的本地电脑上通过控制台记录从 Json 导入的餐厅。但它看起来也没有更新。 我去了 React js 文档,但也没有得到任何明确的答案。 许多解决方案是针对后端有适当的 JSON 文件而我不知道如何在当前情况下应用它们的情况。

餐厅输入.jsx:

handlechange(e)

    const name=e.target.name;
    const value=e.target.value;
    this.setState((prevState)=>
                      prevState.restaurant[name]=value;
                      returnrestaurant:prevState.restaurant;
                    );
     

handleSave=(e)=>

    this.props.onSave(this.state.restaurant);
    this.setState(
        restaurant:Object.assign(,Init_value),
         error:);

         e.preventDefault();

App.js:

class App extends React.Component 
    constructor(props)
      super(props);
     this.handlerestaurantclick=this.handlerestaurantclick.bind(this);
     this.saveRestaurant=this.saveRestaurant.bind(this);
     this.state=restaurants:Restaurantlist,showcomponent:false,
                 restaurantClicked:-1,newrestaurant:
     

    saveRestaurant(restaurant)
          if(!restaurant.key)
          restaurant.key= Object.keys(this.state.restaurants).length;
          this.setState((prevState)=>
             
               let restaurants=prevState.restaurants;
               restaurants[restaurant.key]=restaurant;
               returnrestaurants;
              );

       

RestaurantList.jsx:

 let list=[];
 restaurantArray.forEach((item,index)=>
               list.push(<Restaurant key=index name= 
               item.restaurantName 
                adress=item.address ratings=item.ratings onClick= 
               ()=>this.handleclick(index)> </Restaurant>))
             return(<div className="restaurant-list">
             <Filter getmin_filter=this.state.handle_min get_max= 
             this.state.handle_max/>
             list
           </div>);

【问题讨论】:

不确定,但您似乎在 RestaurantList.jsx 的 forEach 循环中返回了一个值,但根据文档developer.mozilla.org/en-US/docs/Web/javascript/Reference/…,forEach 没有返回某些内容我假设您在某处错过了) 不,返回的是渲染函数,它在此处提供的代码中不可见 【参考方案1】:

如果在父组件上发生更改,则属性不是状态,子组件不会重新渲染,因此您必须使用“componentDidUpdate”检查下面的链接

Re-render React component when prop changes

任何不是父子之间的通信,您都可以使用事件或状态管理器,如 redux

【讨论】:

以上是关于使组件添加新组件的问题的主要内容,如果未能解决你的问题,请参考以下文章

添加一个新组件,啥是 Interop.dll 文件?

如何向 NetBeans 添加新的 Java 组件?

将新组件动态添加到 JSF 组件树时重复 id

如何在 video.js 上添加新组件(按钮)?

添加新参考后如何查看工具箱中的组件?

在组件之间添加数据 Angular