Javascript 如何在不呈现子组件的情况下在React组件之间传递数据
我正在尝试从我的textService获取数据到Error500页面,而不呈现Error500页面。如何在不呈现子组件的情况下将状态数据作为道具传递 我试着这么做,但似乎效果不太好 这是我在父类中的代码Javascript 如何在不呈现子组件的情况下在React组件之间传递数据,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我正在尝试从我的textService获取数据到Error500页面,而不呈现Error500页面。如何在不呈现子组件的情况下将状态数据作为道具传递 我试着这么做,但似乎效果不太好 这是我在父类中的代码 constructor(props){ super(props); this.state = { url:"", data: [], isLoaded: false, test: "Will it work?", }
constructor(props){
super(props);
this.state = {
url:"",
data: [],
isLoaded: false,
test: "Will it work?",
}
}
componentDidMount() {
this.fetchImg(process.env.REACT_APP_TEXT_API);
this.passError500();
}
fetchImg(url){
const proxyurl = "https://cors-anywhere.herokuapp.com/";
fetch(proxyurl+url)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded:true,
data:json,
test: "Will it work?",
})
})
}
passError500(){
return(
<Error500Page test={this.state.test}/>
)
}
建造师(道具){
超级(道具);
此.state={
url:“”,
数据:[],
isLoaded:false,
测试:“它会工作吗?”,
}
}
componentDidMount(){
this.fetchImg(process.env.REACT\u APP\u TEXT\u API);
这个.passeror500();
}
fetchImg(url){
常量proxyurl=”https://cors-anywhere.herokuapp.com/";
获取(代理url+url)
.then(res=>res.json())
。然后(json=>{
这是我的国家({
isLoaded:是的,
数据:json,
测试:“它会工作吗?”,
})
})
}
过路人500(){
返回(
)
}
这就是我如何尝试访问child类中的道具
import TextService from 'src/app/services/textService/textService';
const Error500Page = (props) =>
{
console.log(props.test);
return (
<div className="flex flex-col flex-1 items-center justify-center p-16">
<div className="max-w-512 text-center">
<FuseAnimate animation="transition.expandIn" delay={100}>
<Typography variant="h1" color="inherit" className="font-medium mb-16">
{props.test}
</Typography>
</FuseAnimate>
从'src/app/services/TextService/TextService'导入TextService;
常量错误500页=(道具)=>
{
控制台日志(道具测试);
返回(
{props.test}
当我在控制台上记录props.test时,我没有定义。你知道我该怎么做吗?谢谢尝试使用
this.props访问props
const Error500Page = (this.props) =>
也许你会得到你想要的:
导出功能错误500页(测试){
返回
{test}
;
}
导出默认值{Error500Page};
您需要调用this.passeror500()
在更改状态(设置this.state.test
之后)后,您可以在render
方法中执行该操作,或者使用类似以下内容:this.setState({….test:“它会工作吗?”),this.passeror500)
我不想在那个类中渲染组件。你可以在渲染中调用函数而不渲染组件。什么时候渲染Error500Page
呢?我认为React不是那样工作的。要查看传递的道具,你需要渲染子组件。如果你不渲染子组件,那么y尝试转到该组件,React如何知道哪个父级注入了什么道具?该组件是无状态的,因此您不需要“this”。如果您使用“this”,将抛出“无法读取未定义属性'props'”关键字。那么为什么不使用功能组件呢?功能组件是什么意思?功能组件自React 16.8 Hooks更新以来是新的;),请确保您使用的是最新的React版本