我有一些子组件,这些子组件在要在父组件中使用的函数中设置了状态“ imageLink”。但是即使使用setState设置,我也总是会得到null。
task.then(() => {
taskSnapshot.ref.getDownloadURL().then(downloadURL => {
const image = {uri: downloadURL};
this.setState({imageLink: image});
});
});
在父组件中
db.collection('childs')
.add({
name: this.state.name,
firstname: this.state.firstname,
birthDate: this.state.chosenDate,
gender: this.state.gender,
birthLocation: this.state.birthLocation,
rang: this.state.rang,
imageLink: this.state.imageLink,
});
答案 0 :(得分:1)
反应组件不会共享状态/ setState方法。
您想要的是lift the child component's state。
不是在子组件中包含状态“ imageLink”,而是将其添加到父组件的状态(看起来已经完成了),然后通过以下方法传递一种方法来将该值设置为子组件道具:
class Child extends React.Component {
// Here's your method
someMethod = () => {
// Now we can use the "setImageLink" prop to set the parent component's "imageLink" state value.
const { setImageLink } = this.props;
task.then(() => {
taskSnapshot.ref.getDownloadURL().then(downloadURL => {
const image = { uri: downloadURL };
setImageLink(image);
});
});
}
render () {
return null;
}
}
class Parent extends React.Component {
state = {
imageLink: "",
// ... rest of your state
}
setImageLink = (imageLink) => {
this.setState({ imageLink });
}
render () {
const { imageLink } = this.state;
return (
<Child setImageLink={this.setImageLink} />
);
}
}
答案 1 :(得分:0)
const ParentComponent = (props) => {
return(
<ChildComponent imageLink={(imageLink)=> this.setState({imageLink: imageLink})}/>
)
}
const ChildComponent = (props) => {
const sendLinkToParent =(link) => {
props.imageLink(link);
}
return(
// your code
)
}
您可以调用sendLinkToParent将链接传递到父组件。