How to use Context API to pass down a state while using a Router in React JS

自作多情 提交于 2021-02-11 14:11:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!