Reactjs 如何使用useContext钩子更新数组?
我已经使用createContext设置了一个上下文,我希望它更新将在不同组件中使用的数组。此阵列将接收从API(通过Axios)获取的数据 代码如下: Context.jsReactjs 如何使用useContext钩子更新数组?,reactjs,react-hooks,Reactjs,React Hooks,我已经使用createContext设置了一个上下文,我希望它更新将在不同组件中使用的数组。此阵列将接收从API(通过Axios)获取的数据 代码如下: Context.js import React, { useState } from "react"; const HeroContext = React.createContext({}); const HeroProvider = props => { const heroInformation = { heroesC
import React, { useState } from "react";
const HeroContext = React.createContext({});
const HeroProvider = props => {
const heroInformation = {
heroesContext: [],
feedHeroes: arrayFromAPI => {
setHeroesContext(...arrayFromAPI);
console.log();
}
};
const [heroesContext, setHeroesContext] = useState(heroInformation);
return (
<HeroContext.Provider value={heroesContext}>
{props.children}
</HeroContext.Provider>
);
};
export { HeroContext, HeroProvider };
import React, { useContext, useEffect } from "react";
import { HeroContext } from "../../context/HeroContext";
import defaultSearch from "../../services/api";
const HeroesList = () => {
const context = useContext(HeroContext);
console.log("Just the context", context);
useEffect(() => {
defaultSearch
.get()
.then(response => context.feedHeroes(response.data.data.results))
.then(console.log("Updated heroesContext: ", context.heroesContext));
}, []);
return (
//will return something
)
在Component.js中,我导入了defaultSearch,这是对API的调用,该API获取我想要推送到数组的数据
如果您现在运行代码,您将看到它将仅在上下文中控制台一个寄存器的上下文。我不想要它。。。我在这里的用意是多取些寄存器我不知道为什么它只带来一个寄存器。
不管怎么说,做了我上面做的所有这些事情,它不会填充数组,因此我不能在另一个组件中使用数组数据
有人知道如何解决这个问题吗?我的错误在哪里?问题是您正在声明一段状态以存储整个上下文对象,但随后您将该状态设置为一个单独的非结构化数组 因此,您正在初始化heroesContext
const heroInformation = {
heroesContext: [],
feedHeroes: arrayFromAPI => {
setHeroesContext(...arrayFromAPI);
console.log();
}
};
但随后将其替换为…arrayFromAPI
此外,您没有正确地展开阵列。您需要将其分散到一个新数组中,否则它将单独返回值:setHeroesContext([…arrayFromAPI])代码>
我会这样做:
const HeroContext = React.createContext({});
const HeroProvider = props => {
const [heroes, setHeroes] = useState([]);
const heroContext = {
heroesContext: heroes,
feedHeroes: arrayFromAPI => {
setHeroes([...arrayFromAPI]);
}
};
return (
<HeroContext.Provider value={heroContext}>
{props.children}
</HeroContext.Provider>
);
};
export { HeroContext, HeroProvider };
const HeroContext=React.createContext({});
const HeroProvider=props=>{
const[heromes,setheromes]=useState([]);
常量上下文={
heroesContext:英雄,
feedHeroes:arrayFromAPI=>{
setHeroes([…arrayFromAPI]);
}
};
返回(
{props.children}
);
};
导出{HeroContext,HeroProvider};