我将一个searchObject
从数据库保存到localStorage
并重定向到/discover
onclick:
modelInstance.getSearchFromDB(id).then((searchObject) => {
console.log(searchObject);
modelInstance.setSearchParams(searchObject); // Save search params to localStorage
window.location.assign("/discover");
})
在
discover.js
中,我使用searchObject
对象:class DiscoverContainer extends React.Component {
constructor(props){
super(props);
this.state = {
status: 'NULL',
searchInput: ""
}
}
componentDidMount() {
let searchObject = modelInstance.getSearchParams(); // function that gets search params and eliminates them from localStorage
console.log("searchObject.query:");
console.log(searchObject.query);
if(searchObject){
this.setState({
status: "LOADED",
searchInput: searchObject.query,
positive: searchObject.positive,
negative: searchObject.negative,
total: searchObject.total,
noOfNeutral: searchObject.noOfNeutral,
until: searchObject.until,
placeName: searchObject.location,
});
}
}
render () {
const { stepsEnabled, steps, initialStep} = this.state;
}
return (
<div className="container-discover">
<Search handleStatusChange={this.handleStatusChange} searchInput={this.state.searchInput}/>
</div>
);
如您所见,在
componentDidMount
中,我将this.state.searchInput
设置为searchObject值。我的期望是,这将导致将新值发送到Search
中的render
对象,以便Search
将此值发送到其子级SearchInput
:Search.js:
class Search extends Component {
constructor(props){
super(props);
var today = new Date();
console.log("in Search:");
console.log(props.searchInput);
this.state = {
searchSuggestion: 'Search for tweets here',
anchorEl: null,
page: 0,
placeName: "LOCATION", // === '' ? "LOCATION" : modelInstance.getPlaceName()
placeOptions: modelInstance.getPlaceOptions(),
searchInput: props.searchInput,
}
render(){
return(
<div className='search'>
<Row id='searchInput'>
<SearchInput handleInput={this.handleInput.bind(this)} searchInput={this.state.searchInput} searchSuggestion={this.state.searchSuggestion} page={1}/>
</Row>
</div>
)
}
}
不幸的是,这不起作用。我在
searchObject.query
文件中输出discover.js
(您可以在代码中看到它),并且正确的值在那里。但是,当我在props.searchInput
中输出Search'
时,什么也没有输出。这似乎是因为Search.constructor
在Discover.componentDidMount
之前运行。感觉我正在以错误的方式进行操作。将父母的状态传给“孙子”的正确方法是什么? 最佳答案
无需将道具复制到孩子的状态,只需直接在render
中引用道具即可:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchSuggestion: 'Search for tweets here',
anchorEl: null,
page: 0,
placeName: 'LOCATION',
placeOptions: modelInstance.getPlaceOptions(),
};
}
render() {
return(
<div className='search'>
<Row id='searchInput'>
<SearchInput
handleInput={this.handleInput.bind(this)}
searchInput={this.props.searchInput}
searchSuggestion={this.state.searchSuggestion}
page={1}
/>
</Row>
</div>
)
}
}