我不确定我在这里做错了什么。
我希望Main
组件将ajax请求方法传递给子组件InputForm
,这将返回将存储在Main
组件状态中的结果。
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" ));
我没有得到任何结果&amp;我的webpack服务器刷新页面。
答案 0 :(得分:1)
这里的主要问题是您没有在表单提交上调用preventDefault。 另外,获取github repos的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>
);
}
}