与对象反应useEffect

时间:2020-05-09 11:07:11

标签: reactjs use-effect

我正在尝试更新状态。我一直在阅读,为了不完全替换状态,需要使用传播运算符。在将状态附加到先前的状态时,它会进行一些工作,但是我在将状态附加到正确的位置时仍在努力。下面的代码更新了“类别”的状态,但它的状态与“ all_categories”和“ current_category”相同。我希望将获取的对象放入“ all_categories”中。谢谢。

 const [ categories, setCategory ] = useState({
    all_categories: [],
    current_category: 'Cocktail'
  });
  const [recipes, setRecipe] = useState([]);

  useEffect(() => {
    Promise.all(
      [
        fetch(`https://the-cocktail-db.p.rapidapi.com/filter.php?c=${categories['current_category']}`, {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
            "x-rapidapi-key": "xxx"
          }
        }),
        fetch("https://the-cocktail-db.p.rapidapi.com/list.php?c=list", {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
            "x-rapidapi-key": "xxx"
          }
        })
      ]
    )
    .then(([response1, response2]) => {
      return Promise.all([response1.json(), response2.json()])
    })
    .then(([drinks_data, categories_data]) => {
      setRecipe(drinks_data['drinks'])
      setCategory(prev_state => {
        return {...prev_state, ...categories_data['drinks']};
      });
    })
    .catch(err => { console.log(err); });
  },[]);

2 个答案:

答案 0 :(得分:1)

您必须在类别状态下更新all_categories键,并使用如下所示的传播语法合并各个类别值

 setCategory(prev_state => {
    return {
       ...prev_state,
       all_categories: [
           ...prev_state.all_categories,
           ...categories_data['drinks']
       ]
    };
  });

答案 1 :(得分:0)

现在您在类别(all_categories,current_category)中有2个变量,可以使用setCategory函数进行更新,如果您只想更新当前类别,则如下图所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.thcb.app">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:screenOrientation="landscape"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity2"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

现在,您要对类别状态内的current_category对象进行突变,其余部分保持不变,以相同的方式可以对状态内的其余变量进行处理,如果尝试对不存在的变量进行突变,则它将在状态内创建新变量,

让我们看看如何将api的响应值添加到all_categories,

setCategory({...rest, {current_category: 'Vodka'}})