我不确定我在这里做错了什么。
我希望Main
组件将ajax请求方法传递给子组件InputForm
,该子组件将返回存储在Main
<中的结果< code>
组件状态。
中的结果<>
class Main extends React.Component {
constructor( props ){
super( props );
this.state = {
fetching : false,
repos : {}
};
this.getGitHubRepo = this.getGitHubRepo.bind( this );
}
getGitHubRepo( user ){
this.setState({ fetching : true });
console.log( "form submitted!", user );
axios.get( user )
.then(( response ) => {
console.log( "response =>", response );
})
.catch(( error ) => {
console.log( "error => ", error );
});
}
render(){
return(
<div className = "appContainer">
<InputForm getGitHubRepo = { this.getGitHubRepo } />
</div>
);
}
}
class InputForm extends React.Component{
constructor( props ){
super( props );
this.state = {
inputValue : "",
};
this.recordInput = this.recordInput.bind( this );
}
recordInput( e ){
this.setState({ inputValue : e.target.value });
}
render(){
let getPath = `https://api.github.com/${this.state.inputValue}`;
return(
<form onSubmit = {() => this.props.getGitHubRepo( getPath )}>
<label htmlFor = "user_input">
Github Username
</label>
<input id = "user_input"
type = "input"
onChange = { this.recordInput } />
<input type = "submit" value = "get repos" />
</form>
);
}
}
ReactDOM.render( <Main />, document.getElementById( "app" ));
我没有得到任何结果,我的 webpack 服务器刷新了页面。
请您参考如下方法:
这里的主要问题是您没有在表单提交时调用preventDefault。 另外,获取 github 存储库的 url 是错误的,但这是次要的。
检查更新后的jsbin:https://jsbin.com/sujakexamo/1/edit?js,output
class InputForm extends React.Component{
constructor( props ){
super( props );
this.state = {
inputValue : "",
};
this.recordInput = this.recordInput.bind( this );
this.submit = this.submit.bind(this);
}
recordInput( e ){
this.setState({ inputValue : e.target.value });
}
submit (e) {
e.preventDefault();
this.props.getGitHubRepo( `https://api.github.com/users/${this.state.inputValue}/repos` );
}
render(){
return(
<form onSubmit = {this.submit}>
<label htmlFor = "user_input">
Github Username
</label>
<input id = "user_input"
type = "input"
onChange = { this.recordInput } />
<input type = "submit" value = "get repos" />
</form>
);
}
}