如何在渲染中一次又一次地停止函数调用

How to stop function again and again calling in render

我是 React 新手,我从 redux 获取数据,首先,我从 accounts 从 redux 获取一个对象,然后我将它传递给 redux 中的函数并在 numReg 中设置一个值减速器.

当我在操作中通过 this.props.fetchAccountDetail(data) 调用函数时,它会向 API 发送请求并从 API 获取数据并将其保存在 reducer 或存储中。当我在渲染中调用函数时 this.getDataFromAccount(accountDetail.num),它进入无限循环

我想要 return 中的数据,它应该只 运行 一次。

import React, { Component } from 'react'
import { fetchAccountDetail, } from '../../../actions'

class myclass extends Component {
  state = {
    num : ''
  };

  getAccounts = (data) => {
    if (!data) { return; }
    return data.find(item => item.id == this.props.match.params.id);
  }

   getDataFromAccount = (data) => {
      this.props.fetchAccountDetail(data); 
      // This is a api , which provide the result agaisnt 
      // a num and set value in numReg in reducer
   }

  render() {
    const { accounts, numReg } = this.props;
    const accountDetail = this.getAccounts(accounts);
    // Here i will get a match object like  {id :1 , num :12345}

    const test=this.getDataFromAccount(accountDetail.num)
    // When i call this , it stucks in infinite loop , how can i get data only once when it render

    console.log(test)       

    return (
      <div />
    );
  }
}

const mapStateToProps = state => {
  return { accounts : state.accounts.accounts | [{id :1 , num :12345} , {id :2 , num :535234}],
    numReg : state.accounts.numReg  
    //Is a object containg the information of num from accounts
  }
}

export default (compose(
  withStyles(styles),
  connect(mapStateToProps, { fetchAccountDetail,}))(myclass));

从redux中获取数据后应该return变量测试中的数据。

你永远不应该调用数据获取函数或改变渲染中状态的函数。

如果父级重新渲染或仅其内部状态发生变化,渲染可能会被调用多次。 在 render 中调用 fetchAccountDetails 更新 redux store。 Redux 会将新的但相等的数据作为 props 传递到您的组件中。

该组件将重新渲染,因为它的 props 已更改,并将再次调用 fetchAccountDetails => 循环。渲染应该只显示数据!!

对于数据获取,存在 2 个函数。 componentDidMount 将在组件可见后调用。那将是调用 fetch 的好地方。

如果您需要 prop 来获取 的数据,例如 某种 ID(获取该 ID 的数据),您可以使用 componentDidUpdate 里面比较新id和旧id,看是否需要重新取数据

您应该阅读文档并查看一些教程。 希望这可以帮助。

编码愉快。

正如 Domino987 回答的那样,您需要使用 lifecycle methods。下面是它可能的一个例子:

componentDidMount() {
  const { accounts } = this.props;
  const accountDetail = this.getAccounts(accounts);
  const accountData = this.getDataFromAccount(accountDetail.num)
  this.setState({
    account: {
      accountDetail: accountDetail,
      accountData: accountData
    }
  })
}

componentDidUpdate() {
  const { accounts } = this.props;
  const accountDetail = this.getAccounts(accounts);
  const accountData = this.getDataFromAccount(accountDetail.num)
  if (this.state.account.accountData !== this.getDataFromAccount(accountDetail.num)) {
    this.setState({
      account: {
        accountDetail: accountDetail,
        accountData: accountData
      }
    })
  }
}