猿问

如何在 react js 中刷新组件

我使用 React js,文件中有一个名为 .我希望每次单击按钮时都会更新该值。App.jsPersonsPersons


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>

  );

}

在这里你可以看到我的代码和盒子


天涯尽头无女友
浏览 283回答 2
2回答

有只小跳蛙

用于将数据传递到子组件的逻辑是错误的,您必须将其作为 propons 传递,而不是在 subComponent 中导入此外,为了重新呈现每个请求,您必须使用useState&nbsp;hook,它返回您的Value数组及其setter方法所以在应用程序功能内使用let&nbsp;[persons,&nbsp;setPersons]&nbsp;=&nbsp;useState(initialData);然后在公理结果集中使用函数的人setPersons并在你的coponent传递这个人作为道具。EleventHeaderCard看到这支工作笔

慕娘9325324

使用 useState 挂钩。它将在更改时重新呈现组件。const initialValue = [{&nbsp; id: 9,&nbsp; email: "michael.lawson@reqres.in",&nbsp; first_name: "Michael",&nbsp; last_name: "Lawson",&nbsp; avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"},{&nbsp; id: 10,&nbsp; email: "lindsay.ferguson@reqres.in",&nbsp; first_name: "Lindsay",&nbsp; last_name: "Ferguson",&nbsp; avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"}];export default function App() {&nbsp; const [people, setPeople] = useState(initialValue);&nbsp; const handleClick = () => {&nbsp; &nbsp; return axios.get(`https://reqres.in/api/users?page=2`).then(res => {&nbsp; &nbsp; &nbsp; setPeople(res.data.data);&nbsp; &nbsp; });&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <Button color="primary" type="Submit" onClick={handleClick}>&nbsp; &nbsp; &nbsp; click me !!!&nbsp; &nbsp; </Button>&nbsp; &nbsp; <EleventHeaderCard />&nbsp; </div>&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答