【发布时间】:2017-08-23 20:07:16
【问题描述】:
如您所见,我的 handleSearchRequest 函数正在调用一个 API,该 API 稍后由 IconButton 标记内的 onClick 事件调用。
如何在 ComponentWillMount 中加载 API,我仍然可以在 HandleSearchRequest 上写一些东西,比如 setState 或其他东西,这样 Onclick 仍然可以调用这个函数?
class Searcher extends React.Component {
constructor(props){
super(props);
this.state = {
query: '',
application: null
}
}
// componentDidMount () {
//
//
//
// }
handleSearchRequest() {
console.log('this.state', this.state);
const BASE_URL = 'https://itunes.apple.com/search?term';
const FETCH_URL = BASE_URL + '=' + this.state.query;
console.log('FETCH_URL', FETCH_URL);
fetch(FETCH_URL, {
method: 'GET'
})
.then(response => response.json())
.then(json => {
const application = json.results[0];
this.setState({application})
console.log({application})
});
}
render () {
return (
<div style={{position: 'relative'}}>
<IconButton
iconStyle={styles.smallIcon}
style={styles.iconButton}
onClick={() => this.handleSearchRequest()}
>
<Search color={black} />
</IconButton>
<TextField
underlineShow={false}
id="searchId"
value={this.state.query}
fullWidth={true}
style={styles.textField}
inputStyle={styles.inputStyle}
hintStyle={styles.hintStyle}
onChange={event => {this.setState({ query: event.target.value}) }}
onKeyPress={event => {
if (event.key === 'Enter') {
this.handleSearchRequest()
}
}}
/>
<br/>
<br/>
{
this.state.application !== null
?
<ResultItem
{...this.props} {...this.state}
application={this.state.application}
/>
: <div></div>
}
</div>
);
}
}
export default Searcher;
编辑
这是 ResultItem 组件
class ResultItem extends Component {
componentDidMount () {
}
render () {
// console.log ('myProps', this.props);
let application = {
artistName: '',
country: '',
primaryGenreName: '',
trackName: ''
};
if (this.props.application !== null) {
application = this.props.application
}
return (
<div>
<Card style={{width:'30%'}}>
<CardMedia>
<div style={styles.appCard}/>
</CardMedia>
<FloatingActionButton
style={styles.addButton}
backgroundColor={'#CC0000'}
>
<ContentAdd />
</FloatingActionButton>
<CardTitle
title={application.artistName}
subtitle="Application" />
<CardText>
<div>
<div>Name: <b>{application.artistName} </b> </div>
<div>Country:<b>{application.country} </b> </div>
<div>Genre: <b>{application.primaryGenreName}</b> </div>
<div>Song: <b>{application.trackName} </b> </div>
</div>
</CardText>
</Card>
</div>
);
}
}
export default ResultItem;
【问题讨论】:
-
不记得是什么意思?
-
就像,如果我将函数的所有内容都放在 ComponentDidMount 中。那么 handleSearchRequest 将只有 1 行 const application = json.result [0] ,但是这 2 个值(application 和 json)不是全局变量,你知道,就像在 ES5 中一样?无论如何,这样做是一种不好的做法
-
当你想存储信息时,你使用 this.setState({ ... }) 将它存储在组件状态中。就这些。您可以使用 this.state.someProp 从任何组件方法访问状态
-
我只是想像在这个反应模式的书 xzlearning.com/skills/6010 中那样实现它。正如你所看到的,他们在 ComponentDidMount 中有 fetch 调用,只是试图在那里应用模式
-
从componentDidMount调用方法应该没有问题。你到底在纠结什么?