【发布时间】:2020-11-06 22:24:48
【问题描述】:
我正在尝试使用子组件中的 handleUpdate 函数将道具传递给我的顶级组件,并使用这些道具值更新状态。到目前为止,我在控制台日志中没有看到道具出现。我不认为我传递了正确的论点。我已经修补过并且被卡住了。有人可以协助解释他们的推理吗?
子组件中的handleUpdate函数:
search = async (word) => {
try{
// var word = this.state.word.trim();
const data = await MerriamAPI.getWordInfo(word);
if (data){
this.props.handleUpdate({
word: word,
info: data,
versions: data[0].meta.stems,
shortdef: data[0].shortdef[0],
partOfSpeech: data[0].fl,
pronunciation: data[0].hwi.prs[0].mw,
},
}
else{
console.log('No Definition Found')
}
}
catch{
this.setState({error: 'No Definition Found'})
}
console.log(this.props)
}
父组件:
class App extends Component {
state = {
redirect: {},
word: '',
error: '',
info: [],
partOfSpeech: [],
versions: [],
shortdef: "",
pronunciation: "",
}
setRedirect = redirect =>
this.setState({redirect})
handleUpdate = (props) =>
this.setState({word:this.props})
render() {
return (
<>
<Route
render={ routeProps => <Redirector redirect={this.state.redirect} setRedirect={this.setRedirect} {...routeProps} />}
/>
<header>
<nav>
<Link to='/'>My Dictionary</Link>
</nav>
</header>
<main>
<Route
render = { routeProps =>
!routeProps.location.state?.alert ? '' :
<div>
{ routeProps.location.state.alert }
</div>
}
/>
<Switch>
<Route exact path="/" render={ routeProps => <Home handleUpdate={this.handleUpdate} {...routeProps} />} />
<Route exact path="/definition/:word" render={ routeProps => <GetWordContainer word={this.state.word} {...routeProps} />} />
</Switch>
</main>
</>
);
}
}
export default App;
【问题讨论】:
标签: reactjs components state react-props