在 Next.js 13 中在异步函数中尝试访问 Redux 状态时发生错误。

huangapple go评论68阅读模式
英文:

Error while trying to access a redux state inside of async function in next js 13

问题

"使用客户端"
import SearchResults from "./searchResults";
import axios from "axios";

import { useSelector } from "react-redux";

const getRecipe = async () => {
  const response = await axios.get(
    `https://api.edamam.com/api/recipes/v2?type=public&q=cake&app_id=API_ID&app_key=API_KEY`
  );
  const data = await response.data;

  return data;
};

const SearchRecipe = async () => {
  const recipes = await getRecipe();
  const searchTerm = useSelector((state) => state.recipe.value.searchTerm);
  return (
    <div>
      
    </div>
  );
};

export default SearchRecipe;

const searchTerm = useSelector((state) => state.recipe.value.searchTerm);
在这里我尝试从使用Redux Toolkit创建的切片中访问searchTerm状态但当我运行此组件时出现错误无法读取null的属性读取'useContext'),在另一个组件中运行得很好
英文:
"use client"
import SearchResults from "./searchResults";
import axios from "axios";

import { useSelector } from "react-redux";

const getRecipe = async () => {
  const response = await axios.get(
    `https://api.edamam.com/api/recipes/v2?type=public&q=cake&app_id=API_ID&app_key=API_KEY`
  );
  const data = await response.data;

  return data;
};

const SearchRecipe = async () => {
  const recipes = await getRecipe();
  const searchTerm = useSelector((state) => state.recipe.value.searchTerm);
  return (
    <div>
      
    </div>
  );
};

export default SearchRecipe;

const searchTerm = useSelector((state) => state.recipe.value.searchTerm); here i am trying to access the searchTerm state from the slice i created using redux toolkit but when i run this component Error: Cannot read properties of null (reading 'useContext') this error is showing it worked just fine in another components.

答案1

得分: 1

你不能在客户端代码中使用异步组件。异步组件是为服务器端组件设计的。

此外,在你的情况下,你应该使用 useEffect 来获取数据。

英文:

You can not use async components for client side code. Async components are made for server side components.

Also, in your case, you should use useEffect for fetching data.

huangapple
  • 本文由 发表于 2023年7月27日 23:06:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定