问题
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.
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>
);
}
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>
)
回答1:
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
)
}
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>
);
}
回答2:
ApiProvider
<ApiContext.Provider value={{data, setData}}>
Child component
const context = useContext(ApiContext);
console.log(context.data);
context.setData(123);
来源:https://stackoverflow.com/questions/61137644/how-to-use-context-api-to-pass-down-a-state-while-using-a-router-in-react-js