admin管理员组文章数量:1328808
I am trying to access my prop "post" from my parent. I can access it inside render(), but not above where I have my getCom(). How can I make the prop available in functions and not only in the render? I tried to use this.item.id.bind(this)
, but that does not work.
Parent:
<LoadComments post={item.id}/>
Child
class LoadComments extends Component {
getCom = async () => {
// Thid does not work
this.unsubscribe = await firestore.collection("ments").where("post", "==", this.props.post).onSnapshot((querySnapshot) => {
// Rest of code
}
render() {
return (
// This works:
{this.props.post}
)
}
I am trying to access my prop "post" from my parent. I can access it inside render(), but not above where I have my getCom(). How can I make the prop available in functions and not only in the render? I tried to use this.item.id.bind(this)
, but that does not work.
Parent:
<LoadComments post={item.id}/>
Child
class LoadComments extends Component {
getCom = async () => {
// Thid does not work
this.unsubscribe = await firestore.collection("ments").where("post", "==", this.props.post).onSnapshot((querySnapshot) => {
// Rest of code
}
render() {
return (
// This works:
{this.props.post}
)
}
Share
Improve this question
edited Sep 15, 2018 at 16:29
vemund
asked Sep 15, 2018 at 16:13
vemundvemund
1,8174 gold badges31 silver badges44 bronze badges
3
- Are you super(ing) props? – Saddy Commented Sep 15, 2018 at 16:17
-
Are you passing an
id
prop? – Colin Ricardo Commented Sep 15, 2018 at 16:19 -
Am I missing something? You don't have a prop named
id
. You have a prop namedpost
.this.props.id
orthis.props.item.id
isundefined
. You havethis.props.post
here. – devserkan Commented Sep 15, 2018 at 16:20
2 Answers
Reset to default 4To use the value of
item.id
in your child ponent what you should do is:
In Parent:
<LoadComments post={item.id}>
In Child Component:
class LoadComments extends Component {
async getCom(props) => {
// This would work now
this.unsubscribe = await firestore.collection("ments").where("post", "==",
props.post).onSnapshot((querySnapshot) => {
// Rest of code
}
render() {
const props = this.props;
return (
{this.props.post}
getCom(props)
)
}
You have to store the props in a static ponent in render method and then pass the props to the function declared outside the render method.
As you see you pass id
as post
to your child ponent :
<LoadComments post={item.id}/>
so you must use this :
this.props.post
if you want to use id you must pas it as id
like this :
<LoadComments id={item.id}/>
本文标签: javascriptUse props outside of renderStack Overflow
版权声明:本文标题:javascript - Use props outside of render - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742216599a2434681.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论