【问题标题】:React parent component update when child component alters database当子组件更改数据库时反应父组件更新
【发布时间】:2018-04-22 23:20:28
【问题描述】:

所以我有一个父组件,它是一个食物列表,食物列表是通过对我的 api 查询我的 mongodb 数据库的获取请求接收的。

每个食物项都保存在一个 div 中,该 div 是一个子组件,每个 div 内部是另一个子组件,一个删除按钮。当按下删除按钮时,它会从我的 mongodb 数据库中删除该食物项目。目前,当从数据库中删除项目时,父组件不会自动更新,我必须刷新页面,以便它发出另一个获取请求并取回新数据。

我怎样才能让它在我的数据库中的数据发生变化时自动更新。

抱歉措辞,我不确定如何问这个问题。感谢您的帮助。

这是最顶层的组件,当组件挂载时发出一个获取请求

componentWillMount(){
    console.log('lol')
    fetch('http://localhost:3001/getDiet')
    .then((res)=>{
      return res.json()
    })
    .then((data)=>{
      console.log(data)
      var totalsObject = this.getUserTotal(data.diet)
      this.setState({
        dietArray: data.diet,
        ready:true,
        userTotals:{
          calories: totalsObject.calorie,
          protein: totalsObject.protein,
          carbohydrates: totalsObject.carbohydrates,
          fat: totalsObject.fat,
          sugar: totalsObject.sugar
        }
      })
    })
    .catch((error)=>{
      console.log(error)
    })
  }


  render(){
    return(
      <div className="user-diet-container">



        {this.state.ready ?
          <div className="diet-list-container">
          <h1>Your Diet</h1>
          <div className="user-totals">
            <h2>Diet Totals</h2>
              <ul>
                <li>Calories:{this.state.userTotals.calories}g</li>
                <li>Protein:{this.state.userTotals.protein}g</li>
                <li>Carbohydrates:{this.state.userTotals.carbohydrates}g</li>
                <li>Fat:{this.state.userTotals.fat}g</li>
                <li>Sugar:{this.state.userTotals.sugar}g</li>

              </ul>

          </div>

            {this.state.dietArray.map(function(item,i){
              return(

            <div key ={i}>
              <DietParcel values={item} id={i}/>
            </div>
            )
          },this)}
            </div>

          : <h1>here is your diet</h1>}
      </div>
    )
  }
}

在该组件内部是一个子组件,它被创建 x 次,具体取决于从原始获取请求返回的食品数量

    class DietParcel extends Component{
      constructor(props){
        super(props)
        this.state={
          id: "component" + this.props.id,

        }
      }

      something(){
        console.log("lol")
      }
      render(){
        return(
          <div  className="diet-item" ref={this.state.id}>
           {this.props.values.name}<br/>
          Calories:{this.props.values.calorire}<br/>
          Portion: {this.props.values.portion}<br/>
          <h3>Nutritional Information</h3>

          <ul>
            <li>Protein:{this.props.values.nutrition[0].protein}g</li>
            <li>Carbohydrates:{this.props.values.nutrition[1].carbs}g</li>
            <li>Fat:{this.props.values.nutrition[2].fat}g</li>
            <li>Sugar:{this.props.values.nutrition[3].sugar}g</li>

           </ul>
           <DeleteButton onClick={this.something.bind(this)} values={ this.props.values} component={this}/>
        </div>

        )

      }
    }
    export default DietParcel;

最后是作为 DietParcel 组件的子组件的删除按钮,单击它会从数据库中删除该特定项目。

class DeleteButton extends Component{

  componentDidMount(){
  }
  deleteComponent(){


  }
  deleteItem(){
    myDietApi.removeSingleItem({id:this.props.values._id})
    .then((res)=>{
      console.log(res)
    })
  }

  render(){
    return(
      <button className="DeleteButton" onClick={this.deleteItem.bind(this)}>x</button>
    )
  }
}
export default DeleteButton;

【问题讨论】:

  • 请出示您的代码
  • 好吧,我认为这更像是一个与反应逻辑有关的问题,我很抱歉。我现在就把它放上来。

标签: javascript reactjs


【解决方案1】:

阅读您的描述后(没有任何代码示例),我猜您的应用程序的结构如下:

<FoodList>
  <FoodItem>
    <DeleteButton />
  </FoodItem>
  <FoodItem>
    <DeleteButton />
  </FoodItem>
  <FoodItem>
    <DeleteButton />
  </FoodItem>
</FoodList>

另外,我假设您在FoodList 中映射一组食物(类似于state 道具),因此您可以将每个FoodItem 与其子项一起渲染。

我的建议是仅将这个数据库获取食物删除保留在FoodList 中。每当您想删除食物时,DeleteButton 将食物 idindex 或您可能需要的任何标识符发送到 FoodItem,从而将其传播到 FoodList

话虽如此,我将删除该项目:

deleteFood(foodId) {
  // send request to delete food from your DB
  ...

  // remove food with foodId from state
  const index = this.state.foods.findIndex(food => food.id === foodId)

  this.state({
    foods: [
      ...this.state.foods.slice(0, index), // gets every food before
      ...this.state.foods.slice(index + 1) // gets every food after
    ]
  })
}

【讨论】:

  • 好吧,我不知道你可以发送信息备份,我该怎么做?我也添加了我的代码
  • 你可以通过 props 向上传播信息。例如:在DeleteButton 中设置onClick 属性。
  • 好的,所以 onclick 函数将是在父组件中创建然后作为道具传递的函数?出于好奇,redux 会让我避免这种情况,我刚开始阅读它。
  • redux 肯定会帮助你:)
猜你喜欢
  • 2017-04-17
  • 1970-01-01
  • 2019-12-04
  • 2021-07-07
  • 2017-05-05
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多