将反应中的功能组件转换为基于类的组件

我有一个非常基本的问题我有一个 JSON 数组,我可以使用


const [elements, setElements] = useState([]);

  useEffect(() => {

    const res = async () => {

      const result = await axios.get('/data');

      const data = result.data;

      setElements(elements => [...elements, ...data]);

    };

    res();

  }, []);

我想将它们转换为基于类的组件,当我尝试在 setState 中复制时,我得到 []。代码如下


import React, { Component } from 'react';

import './App.css';

import axios from 'axios';

import Element from './components/Element';

class App extends Component {

  constructor(props) {

    super(props);

    this.state = { elements: [] };

  }

  componentDidMount() {

    const res = async () => {

      const result = await axios.get('/data');

      const data = result.data;

      console.log(data);

      this.setState({ elements: data });

    };

    res();

  }

  render() {

    console.log(this.state.elements);

    return (

      <div className='wrapper'>

        <div id='table'>

          {this.state.elements.map(element => (

            <Element elements={element} key={element._id} />

          ))}

        </div>

      </div>

    );

  }

}


export default App;

这是我得到的 JSON


(119) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]   



月关宝盒
浏览 122回答 2
2回答

MMMHUHU

问题在于您如何尝试在 React 组件上设置状态,也许您可以尝试以下操作:this.setState({ elements: data});您可以尝试将您componentDidMount()的更新为以下内容:async componentDidMount() {&nbsp;const {data} = await Axios.get('/data');&nbsp;this.setState({ elements: data });}希望这有帮助!

子衿沉夜

为了使代码相等,应该这样写this.setState(state => ({&nbsp; &nbsp;elements: [...state.elements, ...data]}));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript