扫码关注官方订阅号
ringa_lee
构造方法里修改this.state有问题吧,应该用getInitialState,或者写在componentDidMount里面
如果你调用了外部的一些代码库,在好都是在componentWillUnmount这个周期中把引用的组件detroy,一般库都会有这个方法的
好吧,那我在改一改代码修改后的代码:1、组件名开头字母请大写!2、在componentWillMount设置state初始状态,当然,在didMount也行。3、修改ajax。
class Yewu extends Component{ constructor(props){ super(props) } componentWillMount() { this.setState({ loading: true, error: null, data: null }) } componentDidMount() { $.get('https://api.github.com/search/repositories?q=javascript&sort=stars') .then( value => this.setState({loading: false, data: value}) ) .catch(error => this.setState({loading: false, error: error})) ) } render(){ if (this.state.loading) { return <span>Loading...</span>; } else if (this.state.error !== null) { return <span>Error: {this.state.error.message}</span>; } else { var repos = this.state.data.items; var repoList = repos.map(function (repo, index) { return ( <li key={index}><a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}</li> ); }); return ( <p> <h1>Most Popular JavaScript Projects in Github</h1> <ol>{repoList}</ol> </p> ); } } }
我点击招聘时,招聘组件里面发送了一个ajax请求,但是在这个请求没有回来前,或者说回调没有执行前,我又去点击问答了,此时就会报错啊,报的就是上面的错啊,这里有一个老土的解决方法,就是在构造函数定义一个私有变量 this.aa 反正随便叫个什么;
发送ajax时 this.aa = ajax({...});
当组件卸载时;要做一件重要的事情,清除刚才发出的还没有相应的回调要这么干:
componentWillUnmount(){ console.log("222") this.aa.abort(); }
但是这是用jquery的ajax;当然问题到这已经解决了,但是咱们不妨深入思考下,如果,发送ajax请求返回的不是XHR而是一个Promise,那么用什么方法可以组织这个Promise的执行呢;这就是上面的问题了,希望大家给个解决方案啊,基本就是在componentWillUnmount里面终端promise的回调
componentWillUnmount
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
构造方法里修改this.state有问题吧,应该用getInitialState,或者写在componentDidMount里面
如果你调用了外部的一些代码库,在好都是在componentWillUnmount这个周期中把引用的组件detroy,一般库都会有这个方法的
好吧,那我在改一改代码
修改后的代码:
1、组件名开头字母请大写!
2、在componentWillMount设置state初始状态,当然,在didMount也行。
3、修改ajax。
我点击招聘时,招聘组件里面发送了一个ajax请求,但是在这个请求没有回来前,或者说回调没有执行前,我又去点击问答了,此时就会报错啊,报的就是上面的错啊,
这里有一个老土的解决方法,就是在构造函数定义一个私有变量 this.aa 反正随便叫个什么;
发送ajax时 this.aa = ajax({...});
当组件卸载时;要做一件重要的事情,清除刚才发出的还没有相应的回调要这么干:
但是这是用jquery的ajax;当然问题到这已经解决了,但是咱们不妨深入思考下,如果,发送ajax请求返回的不是XHR而是一个Promise,那么用什么方法可以组织这个Promise的执行呢;
这就是上面的问题了,希望大家给个解决方案啊,基本就是在
componentWillUnmount里面终端promise的回调