在 React JS 中使用路由器时如何使用 Context API 传递状态

How to use Context API to pass down a state while using a Router in React JS(在 React JS 中使用路由器时如何使用 Context API 传递状态)
本文介绍了在 React JS 中使用路由器时如何使用 Context API 传递状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上下文 API 文件设置,它有一个状态和一个从 API 获取数据并设置状态的函数,我想将状态传递给我的其他组件.在我的 App.js 中,我使用 React-Router 来指定路由.如何在使用 React-Router 的同时使用 Context API 将状态传递给这些组件.

我的 ApiContext.js 文件如下所示:

import React, {useState, createContext } from 'react';导出 const ApiContext = createContext();export const ApiProvider = async (props) =>{常量 [数据,setData] = useState(null);const getURL = 'https://examplefetchsite.com';常量响应 = 等待 fetch(getURL).json();设置数据(响应);返回 (<ApiContext.Provider value={[data, setData]}>{props.children}</ApiContext.Provider>);}

我的 App.js 的返回是这样的:

返回 (<ApiProvider><路由器>

<导航栏/><开关><Route path="/" 确切组件={ Dashboard }/><Route path="/create" 组件={ 创建 }/><Route path="/view" 组件={View}/></开关></div></路由器></ApiProvider>)

解决方案

就上下文本身而言,您不必更改提供程序中的任何内容,只需在子组件中执行以下操作:

import React, {useContext} from 'react'从./ApiContext"导入 {ApiContext}const仪表板=(道具)=>{const [数据,setData] = useContext(ApiContext)//你应该可以同时访问数据和setData返回 (//事物)}

但是在 ApiContext.js 中,您没有正确调用 API 请求.您应该使用 useEffect 仅在第一次渲染时获取数据.

import React, {useState, createContext, useEffect} from 'react';导出 const ApiContext = createContext();导出 const ApiProvider = (props) =>{常量 [数据,setData] = useState(null);使用效果(异步()=>;{const getURL = 'https://examplefetchsite.com';常量响应 = 等待 fetch(getURL).json();设置数据(响应);}, [])返回 (<ApiContext.Provider value={[data, setData]}>{props.children}</ApiContext.Provider>);}

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>
    )

解决方案

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>
    );
}

这篇关于在 React JS 中使用路由器时如何使用 Context API 传递状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Swipable Vuetify Tabs with router(带路由器的可滑动Vutify标签)
Vue router - how to have multiple components loaded on the same route path based on user role?(VUE路由器-如何根据用户角色将多个组件加载到同一路由路径上?)
Router Link in VUE JS is not showing active(VUE JS中的路由器链路未显示为活动状态)
Can i import single file component using Vue and Vue Router CDN?(我可以使用VUE和VUE路由器CDN导入单个文件组件吗?)
Vue 3 - Get access to router-view instance in order to call child methods(VUE 3-访问路由器视图实例以调用子方法)
How to replace one parameter in Vuejs router(如何替换Vuejs路由器中的一个参数)