简体   繁体   中英

How does an update from the child component in React get conveyed to the parent?

I am working on a react-express Todo list and cant seem to update the Todo item from the TodoItem component which is in the main App component. when i write the axios function to modify the database from the child component itself the Todo is getting blanked out after a state refresh.

I have tried sending data from the Child component to the parent but with no result.

//App.jsx

                {this.state.data.map(data => (
                  <TodoItem
                    data={data}
                    key={data.id}
                    delete={() => this.removeFromDatabase(data)}
                    edit={() => this.setState({ editing: data.id })}
                    update={(data)=>this.updateDatabase(data)}
                  />
                ))}

//TodoItem.jsx

  handleSubmit = ()=>{
      var data = this.props.data;
      console.log(this.state.editText,data);
    // this.props.update(this.state.editText);
    axios.post('http://localhost:3007/todo/updateTodo',{
        id:data._id,
        update:this.state.editText
    })
    this.setState({isEditing:false})
  }
  //the input where we enter the edited value.
            <input
            type="text"
            style={editStyle}
            value={this.state.editText}
            className="form-control"
            onChange={this.handleChange}
            onBlur = {this.handleSubmit}
            onKeyDown ={this.handleKeydown}
          />



After submitting, the updated value must be shown, instead the todo is blank.

To pass the data from child to parent component you need to use redux . With redux you can can dispatch actions from child component which will mutate the reducer state. And then you can use this state anywhere in your project. In your case this reducer state can be used to update the parent component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM