[英]Props value is Undefined while passing through Context API in REACT
我的上下文 API 提供程序文件(Exp 文件)
import react form 'react';
import {createContext} from "react";
export const ContextforFile = createContext();
export function ContextData(props){
let rdata=props.data
return(
<>
<p>{rdata}</p> //I am able to Get the Data here NO ISSUES TILL HERE
<ContextforFile.Provider value={rdata} >{props.children}</ContextforFile.Provider>
</>
);
}
function A() {
return (
<div>
<ContextData data="Sara" />
</div>
);
}
export default A;
我的 App.js 文件
import Exp, { ContextData } from './afterlogin/patirel/patmain';
import Experiment from './experi';
import {Routes,Route} from 'react-router-dom';
import * as React from 'react';
function App() {
return (
<ContextData>
<div>
<Routes>
<Route index element={<Exp/>} />
<Route path="/experi" element={<Experiment/>} />
</Routes>
</div>
</ContextData>
);
}
export default App;
只有 props.data 值不会出现在这里,而其他值可以很容易地获得这是 Experi 文件我想在哪里获取我的值我的消费者文件
import * as React from 'react';
import { useContext } from 'react';
import { ContextforFile } from './afterlogin/patirel/patmain';
export default function Experi(){
const first= useContext(ContextforFile);
return(
<div>
<h1>ISSUE is Here Other VALUES are COMING BUT NOT props.data: {first}</h1>
</div>
);
}
请帮忙! 已经好几天了,我无法弄清楚我错过了什么? 我该如何解决?
您的函数ContextData
不返回任何内容。 Yoo 应该返回ContextforFile.Provider
获得未定义值的可能性可能很多。
例如:
也许,你从props.data得到 undefined 。 可能是因为您没有为createContext提供默认值。
尝试以下步骤,这些可能会对您有所帮助。
export const ContextforFile = createContext([value it could be any thing like array, string or object etc.]);
你的版本: const first= useContext(ContextforFile);
推荐版本: const useFirst= () => useContext(ContextforFile);
const first= useFirst()
在这里你可以找到不同之处:沙盒示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.