英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论