简体   繁体   English

在父 state 使用获取请求更改后重新渲染子

[英]Re-render child after parent state change with get request

So I'm a beginner with react and I was wondering how to re-render the child after setting the state in the parent (from the child).所以我是一个有反应的初学者,我想知道如何在父级(来自子级)中设置 state 后重新渲染子级。 Here's a code sample.这是一个代码示例。 I have a function that calls a GET request using Axios and when I press the button in the child component ideally it will update the state in the parent and also re-render the child but it only does the former.我有一个 function 使用 Axios 调用 GET 请求,当我按下子组件中的按钮时,理想情况下它会更新 state 只在前一个子组件中,但它也重新生成。

Parent:家长:

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}/>)
    }

    // ...

Child:孩子:

class Child extends Component {
    // ...

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

Also, are you supposed to make a local state in the Child and set it as a copy of the Parent's state or just passing it down as a prop is okay?另外,您是否应该在子级中创建本地 state 并将其设置为父级 state 的副本,或者只是将其作为道具传递可以吗?

Your parent component holds the data and the child uses it.您的父组件保存数据,子组件使用它。 It seems to me you're doing it the right way.在我看来,您的做法是正确的。 Here is a fully working example: Codesandbox这是一个完整的示例: 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} />;
  }
}

Note I renamed your child prop fetchData into onAction (I don't know what's the name of the action that triggers a refresh, could be onRefresh ).请注意,我将您的子道具fetchData重命名为onAction (我不知道触发刷新的操作的名称是什么,可能是onRefresh )。 It's always best to see components props with separation between data attributes and event attributes .始终最好看到将数据属性事件属性分开的组件道具。

Even standard components have it this way: <input value={user.firstname} onChange={doSomething} /> .即使是标准组件也有这种方式: <input value={user.firstname} onChange={doSomething} /> So, better to prefix events by on , then the parent decides what to do with it.因此,最好在事件前加上on ,然后由父母决定如何处理它。 It's not the child's concern.这不是孩子的问题。

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>
        ))}
      </>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在状态更改时重新渲染子组件(父级)reactjs - how to re-render child component on state change(Parent) reactjs 如何在获取请求和 state 更改后重新渲染组件? - How to re-render component after fetch request and state change? 当我更改父组件 state 时,为什么我的 React 子组件没有获取值(重新渲染)? - Why doesn't my React child component get value (re-render) when I change the parent state? 当子组件触发对父组件的状态更改时如何防止父组件重新渲染 - How to prevent parent component re-render when child component triggers a state change to parent 当父组件的状态发生变化时,如何更新(重新渲染)React 中的子组件? - How to update (re-render) the child components in React when the parent's state change? 为什么我的子组件不会在父级的 state 更改上重新渲染? - Why my child components does not re-render on parent's state change? 在React中重新渲染子组件或更改子状态 - Re-render child component in React or change child state 更改父状态后如何重新呈现子组件? - How to re-render child component when Parent state is changed? 父组件状态改变,子组件不重新渲染 - State changed in parent component, child components do not re-render 反应父组件 state 更新但子不重新渲染 - React parent component state updates but child does not re-render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM