使用 get 请求在父状态更改后重新渲染子项

时间:2021-03-19 00:47:57

标签: javascript reactjs

所以我是 react 的初学者,我想知道如何在父级(来自子级)中设置状态后重新渲染子级。这是一个代码示例。我有一个使用 Axios 调用 GET 请求的函数,理想情况下,当我按下子组件中的按钮时,它会更新父组件中的状态并重新渲染子组件,但它只执行前者。

家长:

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

    fetchData = () => {
       axios
            .get(url)
            .then(res => this.setState({data: res.data}))
    }


    Render() {
        return (<Child data={this.state.data} fetchData={this.fecthData}/>)
    }

    // ...

孩子:

class Child extends Component {
    // ...

    render() {
        const { data, fetchData } = this.props
        // render data
        return <button onClick={fetchData}>Change data then fetch</button>
    }
}

另外,您是应该在 Child 中创建一个本地状态并将其设置为 Parent 状态的副本,还是只是将其作为道具传递下去可以?

1 个答案:

答案 0 :(得分:1)

您的父组件保存数据,子组件使用它。在我看来,你的做法是正确的。这是一个完全有效的示例: Codesandbox

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
    this.updateData = this.updateData.bind(this);
  }

  async fetchData() {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    return response.json();
  }

  updateData() {
    this.setState({ data: [] }) // Creates a flicker, just so you see it does refresh the child
    this.fetchData().then((res) => this.setState({ data: res }));
  }

  render() {
    return <Child data={this.state.data} onAction={this.updateData} />;
  }
}

注意我将您的子道具 fetchData 重命名为 onAction(我不知道触发刷新的操作的名称是什么,可能是 onRefresh)。最好看到组件 props 分离数据属性事件属性

即使是标准组件也是这样:<input value={user.firstname} onChange={doSomething} />。因此,最好在事件前加上 on,然后由父级决定如何处理它。这不是孩子的问题。

class Child extends Component {
  render() {
    const { data, onAction } = this.props;

    return (
      <>
        <button onClick={onAction}>Change data then fetch</button>
        {data.map((item) => (
          <div key={item.id}>
            {item.id} - {item.title}
          </div>
        ))}
      </>
    );
  }
}