【发布时间】:2017-02-20 18:52:35
【问题描述】:
我需要测试fetchData() 函数。在过去的 3 个小时里,我一直在尝试遵循 this(和许多其他)教程,并试图让它与我的功能一起工作,但到目前为止还没有运气。无论如何,我最好还是想用另一种方式来做,因为我认为 jQuery 和 React 不应该一起使用。
我基本上想检查 1) 是否在提交搜索表单时调用该函数(单击 SearchForm 中的按钮)以及 2) 检查数据是否返回。
请问有人对如何开始有任何建议吗?
谢谢
首页
export default class Home extends Component {
constructor() {
super();
this.state = {
value: '',
loading: false,
dataError: false
}
this.nodes = [];
this.fetchData = this.fetchData.bind(this);
}
fetchData(e) {
e.preventDefault();
this.setState({loading: true});
axios.get(`https://api.github.com/search/repositories?q=${this.state.value}`)
.then(res => {
this.nodes = res.data.items.map((d, k) => <RepoItem {...d} key={k}/>);
this.setState({loading: false});
})
.catch(err => {
this.setState({dataError: true});
});
}
render() {
return (
<div className="home-wrapper">
<SearchForm value={this.state.value}
onSubmit={this.fetchData}
onChange={(e) => this.setState({value: e.target.value})}/>
{this.state.loading ?
<Spinner/>:
!this.state.dataError ? this.nodes :
<h1>Oops! Something went wrong, please try again!</h1>}
</div>
);
}
}
回购项目
export const RepoItem = props => (
<div className="repo-item">
<h1>{props.full_name}</h1>
</div>);
【问题讨论】:
-
不确定测试部分,但您可能希望将“this”绑定到您的 fetchData 函数,因此其中的 this.setState 指的是 Home 组件。
-
edit: nvm 我已经有了它,我只是删除了几行来虚拟化组件。不过谢谢!
-
嗯不确定它为什么起作用,但基本上,如果您在函数中引用 this,然后将其传递给另一个组件而不绑定“this”(在您的示例中为 SearchForm),“this”将在 SearchForm 中调用和更新状态时引用该组件,而不是 Home。在您的示例中,您对 onChange 事件使用箭头函数,该事件会自动将自身绑定到 Home 组件,因此 this.setState({value: e.target.value} 会正确更新您在 Home 组件中的状态。
标签: javascript reactjs testing axios