简体   繁体   English

function 未根据更新的 state 值返回更新的数据

[英]function not returning updated data based on updated state value

I am creating a crypto react application and just trying to figure something out in which a function is returning an empty array when I update one of the state values.我正在创建一个加密反应应用程序,只是想弄清楚当我更新 state 值之一时 function 返回一个空数组。 I am thinking it is a race condition.我认为这是一个比赛条件。 It works until there is a state change.它一直有效,直到发生 state 更改。 Please see my code below:请在下面查看我的代码:

So I have a state object.所以我有一个 state object。 And it is returning an array of currencies by default based on the selectedCurrencyState.selectedFromCurrency value, which is a state value.默认情况下,它会根据 selectedCurrencyState.selectedFromCurrency 值返回一组货币,该值是 state 值。 This function basically needs to determine the quoteAsset before returning the object that contains the array of baseCurrencies.这个function基本上需要在返回包含baseCurrencies数组的object之前确定quoteAsset。 swapInfo is the state value containing the mock data. swapInfo是包含模拟数据的 state 值。 The mock data is nested like so:模拟数据嵌套如下:

const getBaseCurrencies = () => {
  const filteredQuoteAssetObj = selectedCurrencyState.selectedFromCurrency
    && swapInfo.find(item =>
      item.quoteAsset === selectedCurrencyState.selectedFromCurrency);
  const currencies = filteredQuoteAssetObj
    && filteredQuoteAssetObj.baseAssets.map(item => item.baseAsset);
  return currencies;
}

Here is the mock data that I am using:这是我正在使用的模拟数据: 在此处输入图像描述

Like I said, it works until the state change of selectedCurrencyState.selectedFromCurrency (switch state from USD to SHIB).就像我说的那样,它一直有效,直到selectedCurrencyState.selectedFromCurrency的 state 更改(将 state 从 USD 切换到 SHIB)。 Afterwards, it returns an empty array.之后,它返回一个空数组。 By default I have the state set to USD as the selectedFromCurrency .默认情况下,我将 state 设置为 USD 作为selectedFromCurrency

Any help or input is appreciated.任何帮助或输入表示赞赏。 Thanks guys!多谢你们!

--UPDATED-- Here is the way I am updating the state by the way. --更新--顺便说一下,这是我更新 state 的方式。 I am using a functional component therefore, using useState.因此,我正在使用功能组件,使用 useState。

  const [swapInfo, setSwapInfo] = useState([]);
  const [fromCurrencies, setFromCurrencies] = useState([]);
  const [selectedCurrencyState, setSelectedCurrencyState] = useState({ selectedToCurrency: null, selectedFromCurrency: null });
const [transactionType, setTransactionType] = useState(TRANSACTION_TYPES.BUY);

  useEffect(() => {
    getSwapPairs()
      .then((res) => {
        setSwapInfo(res.data);
        setFromCurrencies(res.data.map(item => item.quoteAsset));

if (transactionType === 'BUY') {
          setSelectedCurrencyState({ ...selectedCurrencyState, selectedFromCurrency: localStorage.getItem('fromCurrency') || 'USD', selectedToCurrency: symbol || localStorage.getItem('toCurrency') });
        }
        setTransactionType(localStorage.getItem('transactionType', transactionType) || TRANSACTION_TYPES.BUY);
  }, []);


  const handleInvertSelectedAssets = (fromCurrency, toCurrency) => {
    setSelectedCurrencyState({ ...selectedCurrencyState, selectedFromCurrency: toCurrency, selectedToCurrency: fromCurrency });
    localStorage.setItem('toCurrency', fromCurrency);
    localStorage.setItem('fromCurrency', toCurrency);
  };

Here is where I switch the transactionType:这是我切换事务类型的地方:

  const handleTransactionTypeChange = (type) => {
    if (transactionType !== type) {
      setTransactionType(type);
      handleInvertSelectedAssets(selectedCurrencyState.selectedFromCurrency, selectedCurrencyState.selectedToCurrency);
      localStorage.setItem('transactionType', type);
      setAmountState({ toCurrencyAmount: '', fromCurrencyAmount: '' });

    }
  };

Feel like your problem lies in the way you update your state.感觉您的问题在于您更新 state 的方式。 Maybe there is a typo on the updated selectedCurrencyState.selectedFromCurrency or maybe swapInfo is somehow updated in an invalid way?也许更新的selectedCurrencyState.selectedFromCurrency有错字,或者swapInfo以某种无效的方式更新?

Could you fill in more info about how your state is managed?您能否填写有关如何管理 state 的更多信息?

When you update state in React,在 React 中更新 state 时,

The following should not be done以下应该做

this.state = {a:"red", b:"blue"};

if( this.state.b == "blue" ) {
    this.setState({a: "green" });
} 

Instead, do相反,做

this.setState((prevState)=>(
    {a: (prevState.b=="blue")? "green": "red" }
));

In other words, state updates that depend on its previous value, should use the callback argument of the setState .换句话说,state 更新依赖于其先前的值,应该使用setState的回调参数。

Eg: selectedCurrencyState depends on transactionType .例如: selectedCurrencyState取决于transactionType

You can store both (or all state properties) as a single object .您可以将两者(或所有 state 属性)存储为单个 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM