Mar*_*elo 4 reactjs react-hooks
我已经使用createContext设置了一个 Context ,并且希望它更新将在不同组件中使用的数组。该数组将接收从 API(通过 Axios)获取的数据。
这是代码:
上下文.js
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 };
Run Code Online (Sandbox Code Playgroud)
看到上面我创建了上下文,但什么也没设置?这样对吗?我也尝试为数组和函数设置相同的名称(分别为HeroesContex和feedHeroes)。
组件.js
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
)
Run Code Online (Sandbox Code Playgroud)
在Component.js中,我导入了 defaultSearch ,这是对 API 的调用,用于获取我想要推送到数组的数据。
如果您现在运行代码,您将看到它将在Just the context中控制台一个寄存器的上下文。我不想要它......我的目的是获取更多寄存器。我不知道为什么它只带一个寄存器。
不管怎样,做上面我做的所有事情,它并没有填充数组,因此我不能在另一个组件中使用数组数据。
有谁知道如何解决这个问题?我的错误在哪里?
问题是您正在声明一个状态来存储整个上下文对象,但随后将该状态设置为等于单个解构数组。
所以你正在heroesContext初始化
const heroInformation = {
heroesContext: [],
feedHeroes: arrayFromAPI => {
setHeroesContext(...arrayFromAPI);
console.log();
}
};
Run Code Online (Sandbox Code Playgroud)
但随后将其替换为...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 };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10381 次 |
| 最近记录: |