【问题标题】:how to refresh component in react jsreactjs中如何刷新组件
【发布时间】:2020-09-02 05:03:04
【问题描述】:

我用的是React js,App.js文件中有一个变量叫Persons。 我希望每次单击按钮时都更新 Persons 值。

import React from "react";
import "./styles.css";
import Button from "@material-ui/core/Button";
import EleventHeaderCard from "./ElevatedHeaderCard";
import axios from "axios";

export let persons = [
  {
    id: 9,
    email: "michael.lawson@reqres.in",
    first_name: "Michael",
    last_name: "Lawson",
    avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
  },
  {
    id: 10,
    email: "lindsay.ferguson@reqres.in",
    first_name: "Lindsay",
    last_name: "Ferguson",
    avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
  }
];

const handleClick = () => {
  return axios.get(`https://reqres.in/api/users?page=2`).then(res => {
    persons = res.data.data;
    console.log(persons);
  });
};

export default function App() {
  return (
    <div className="App">
      <Button color="primary" type="Submit" onClick={handleClick}>
        click me !!!
      </Button>
      <EleventHeaderCard />
    </div>
  );
}

在这里你可以看到我的codesandbox

【问题讨论】:

  • @Treycos 如果可能,请为我编辑 codeSandbox。看不懂
  • @yaser.barati 见下文答案
  • @SpringerF tnx :)))
  • @yaser.barati 不客气 :)

标签: javascript reactjs setstate use-state


【解决方案1】:

用于将数据传递到 subComponent 的逻辑是错误的,您必须将其作为 props 传递,而不是在 subComponent 中导入

此外,为了重新呈现每个请求,您必须使用 useState 钩子,它返回一个 yourValue 数组及其设置方法

所以在app函数里面使用

let [persons, setPersons] = useState(initialData);

然后在 axios 结果集中使用setPersons函数的人

并在您的 EleventHeaderCard coponent 中将 person 作为 props 传递。

看到这个working pen

【讨论】:

    【解决方案2】:

    使用useState hook。它将在更改时重新渲染组件。

    const initialValue = [
    {
      id: 9,
      email: "michael.lawson@reqres.in",
      first_name: "Michael",
      last_name: "Lawson",
      avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
    },
    {
      id: 10,
      email: "lindsay.ferguson@reqres.in",
      first_name: "Lindsay",
      last_name: "Ferguson",
      avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
    }
    ];
    
    export default function App() {
      const [people, setPeople] = useState(initialValue);
    
      const handleClick = () => {
        return axios.get(`https://reqres.in/api/users?page=2`).then(res => {
          setPeople(res.data.data);
        });
      };
    
      return (
        <div className="App">
          <Button color="primary" type="Submit" onClick={handleClick}>
          click me !!!
        </Button>
        <EleventHeaderCard />
      </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2021-09-16
      • 2018-05-28
      • 2019-05-15
      • 2017-12-29
      相关资源
      最近更新 更多