我正在将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
之前运行。感觉就像我走错了路。将父母的状态传递给“大孩子”的正确方法是什么?
答案 0 :(得分:1)
没有必要将道具复制到孩子的状态,只需直接在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>
)
}
}