删除数据后立即更新

时间:2019-07-31 18:15:28

标签: reactjs

class App extends Component{
  constructor(props){
    super(props);
      this.state = { 
      users:[]
    };
  }

  componentDidMount() {
    axios.get(`http://localhost:3000/employees`)
    .then(res => {
      const users = res.data;
      this.setState({ users });

    })
  }

  render(){
    return(
      <div>
        <Main users= {this.state.users}/>
        <Form/>
      </div>
    );
  }
}

class Main extends Component{
  state = {
    id: ''
  }

  handleChange = event => {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    axios.delete(`http://localhost:3000/employees/${this.state.id}`)
    .then(res => {
      console.log(res);
      console.log("this is" + res.data);
    })
  }

  render(){
    return(
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}

有人可以告诉我为什么在Axios删除请求之后,如何在App组件的users数组中呈现新状态吗?

在App组件中,我试图使this.state.users作为将其发送到Form组件的道具。我的猜测是this.setState({users: res.data})。删除请求可以使用200,但是我需要刷新页面以获得新结果。如何立即更新?

// this is a json object
"employees": [
{
  "id": 8,
  "first_name": "Lteve",
  "last_name": "Palmer",
  "email": "steve@codingthesmartway.com"
},

1 个答案:

答案 0 :(得分:1)

正如Dave在评论中提到的那样,您希望对组件之间的状态负全责。

在博客文章You Probably Don't Need Derived State中也讨论了该主题,其中一个解决问题的方法是将Main“报告回”给App以更新状态。因此,无论App传递onDeleteUser函数,还是传递删除用户的回调,例如onUserWasDeleted

我认为,只需对代码进行最少的更改即可完成后者。

class App extends Component {
  constructor(props) {
    super(props);
    this.onUserWasDeleted = this.onUserWasDeleted.bind(this);
  }

  onUserWasDeleted(userId) {
    // remove user that was successfully removed
    this.setState({ users: this.state.users.filter(user => user.id !== userId) });
  }

  render() {
    return (
      <Main
        users={this.state.users}
        // pass down a callback to Main
        onUserDeleted={this.onUserWasDeleted}
      />
    );
  }
}

class Main extends Component {
  handleSubmit = event => {
    event.preventDefault();
    axios.delete(`http://localhost:3000/employees/${this.state.id}`)
    .then(res => {
      console.log(res);
      console.log("this is" + res.data);
      // call our callback function in App
      this.props.onUserWasDeleted(this.state.id);
    })
  }
}