在React JS中使用路由器时如何使用Context API传递状态 [英] How to use Context API to pass down a state while using a Router in React JS
问题描述
我有一个Context API文件设置,该文件具有一个状态和一个从API提取数据并设置状态的函数,我想将该状态传递给其他组件.在我的App.js中,我正在使用React-Router来指定路由.在使用React-Router的同时,如何使用Context API将状态传递给这些组件.
I have a Context API file setup which has a state and a function which fetches data from an API and sets the state, and i want to pass the state down to my other components. In my App.js, I am using React-Router to specify the routes. How do i pass the state down to these components using Context API, whilst using React-Router.
我的ApiContext.js文件如下所示:
My ApiContext.js file looks like this :
import React, {useState, createContext } from 'react';
export const ApiContext = createContext();
export const ApiProvider = async (props) => {
const [data, setData] = useState(null);
const getURL = 'https://examplefetchsite.com';
const response = await fetch(getURL).json();
setData(response);
return (
<ApiContext.Provider value={[data, setData]}>
{props.children}
</ApiContext.Provider>
);
}
我的App.js的返回看起来像这样:
My App.js's return looks like this :
return (
<ApiProvider>
<Router>
<div>
<NavBar />
<Switch>
<Route path="/" exact component={ Dashboard } />
<Route path="/create" component={ Create } />
<Route path="/view" component={View} />
</Switch>
</div>
</Router>
</ApiProvider>
)
推荐答案
就上下文本身而言,您不必更改提供程序中的任何内容,而只需在子组件中执行以下操作:
In terms of the context itself, you don't have to change anything in your provider and only do something like this in the child components:
import React, {useContext} from 'react'
import {ApiContext} from './ApiContext'
const Dashboard = (props) => {
const [data, setData] = useContext(ApiContext)
//you should have access to both data and setData
return (
//things
)
}
但是,在 ApiContext.js
中,您没有正确调用API请求.您应该使用 useEffect
仅在第一个渲染器上获取数据.
However in the ApiContext.js
you aren't calling the API request properly. You should use useEffect
to fetch the data only on the first render.
import React, {useState, createContext, useEffect} from 'react';
export const ApiContext = createContext();
export const ApiProvider = (props) => {
const [data, setData] = useState(null);
useEffect(async () => {
const getURL = 'https://examplefetchsite.com';
const response = await fetch(getURL).json();
setData(response);
}, [])
return (
<ApiContext.Provider value={[data, setData]}>
{props.children}
</ApiContext.Provider>
);
}
这篇关于在React JS中使用路由器时如何使用Context API传递状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!