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

时间:2019-10-07 18:17:47

标签: javascript reactjs

我有一个非常基本的问题,我有一个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) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]   

2 个答案:

答案 0 :(得分:2)

问题在于您如何尝试在React组件上设置状态,也许您可​​以尝试以下操作:

this.setState({ elements: data});

您可以尝试将componentDidMount()更新为以下内容吗?

async componentDidMount() {
 const {data} = await Axios.get('/data');
 this.setState({ elements: data });
}

希望有帮助!

答案 1 :(得分:1)

要使代码相等,应该这样写

"<span>" + val.joke + "</span>"