【问题标题】:Convert a class component into a function component将类组件转换为函数组件
【发布时间】:2020-12-12 05:45:35
【问题描述】:

我想把这个类组件转换成函数组件。我尝试了很多,但都失败了。问题有解决办法吗?

componentDidMount(){
    const id = this.props.match.params.id;
    getById( parseInt(id) )
    .then(product => {
    this.setState({
      product,
      loading: false
    });
  })
}

【问题讨论】:

  • 也许您可以为您的问题以及您正在努力解决的问题添加更多详细信息

标签: node.js json reactjs react-redux react-hooks


【解决方案1】:

下面的sn-p在类组件中等于componentDidMount

// ...
const [loading, setLoading] = React.useState(false);
const [product, setProduct] = React.useState(void 0);

React.useEffect(() => {
  // Did mount, put your code here
  setLoading(true)
 
  // Fetch done
  .then(product => {
    setLoading(false)
    setProduct(product)
  })

}, []);

【讨论】:

  • 如何更改它以与我一起使用: const id = this.props.match.params.id; getById( parseInt(id) ) .then(product => { this.setState({ product, loading: false }); })
  • 我给你写了一个草稿
  • 我该如何改变这个。道具
  • props 是你的功能组件的参数:const YourComponent = (props) => { //... }
猜你喜欢
  • 2021-12-16
  • 2021-11-24
  • 2022-01-17
  • 2020-01-02
  • 2017-09-27
相关资源
最近更新 更多