【发布时间】:2023-03-31 21:29:02
【问题描述】:
我正在尝试访问无状态组件中传递的道具。情况是这样的: 这是父组件:
function Parent(){
const [value, setValue] = React.useState(true);
return (
<Child value={value} />
)
}
这是子组件:
const Child = (props)=>{
// the line of code I didn't see as related to the problem:
const [otherValue, setOtherValue] = React.useState(true);
console.log(props.value);
return (
// some code that uses the value of the prop to show something
)
}
我得到的只是道具是未定义的。我在这里查看了其他问题,并且我已经阅读了一篇文章,根据它我尝试访问道具的方式是正确的,还是我错了?有人可以在这里帮助我吗?
解决方案:我只是试图将我的子组件变成一个类组件,因为我的子组件包含一个状态,起初我发现将其放入我在这里共享的示例代码中并不相关.所以当我把它变成一个类组件时,一切正常。
所以现在我的问题是,为什么,它是如何工作的,函数和 const 组件不能同时持有两个状态或状态和道具?
现在的代码结构是这样的: 这是父组件:
function Parent(){
const [value, setValue] = React.useState(true);
return (
<Child value={value} />
)
}
这是子组件:
class Child extends React.Component{
constructor(props){
super(props);
this.state = {
otherValue: true
}
}
render(){
console.log(this.props.value);// prints true just fine
return (
// some code that uses the value of the prop to show something
)
}
}
【问题讨论】:
-
使用您共享的代码 sn-p,我看不出有什么问题。
-
控制台日志给我“真实”,而不是“未定义”。
-
我真的不明白我的意思是我有代码的其他部分,但这与我试图使其工作的访问无关,基本上它与代码没有什么不同我已经在这里分享过,但我再次收到道具未定义的错误。您知道在任何情况下这种访问无法正常工作的任何原因吗?
-
您的“之前”版本应该没有问题,我们可能缺少其他一些上下文。如果您在“之前”版本的 CodeSandbox/Codepen 上创建可重现的示例,我们可能会告诉您出了什么问题,否则我们没有足够的信息。
-
@helloitsjoe 我想我现在知道我的应用程序的结构有问题,因为在此之前我需要更改很多,所以我想我会专注于现在,因为我当然不知道如何为我的实际代码编写一个合适的复制示例。谢谢。
标签: reactjs