栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将setState设置为新数据?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将setState设置为新数据?

约定是在

componentDidMount
生命周期方法中进行AJAX调用。看看React文档:https : //facebook.github.io/react/tips/initial-
ajax.html

通过AJAX加载初始
数据在componentDidMount中获取数据。响应到达时,将数据存储在状态下,触发渲染以更新您的UI。

因此,您的代码将变为:https :
//jsbin.com/cijafi/edit?html,js,output

class App extends React.Component {  constructor() {    super();    this.state = {data: false}  }  componentDidMount() {    axios.get('https://jsonplaceholder.typipre.com/posts')        .then(response => { this.setState({data: response.data[0].title})        });  }  render() {    return (     <div>       {this.state.data}     </div>    )  }}ReactDOM.render(<App />, document.getElementById('app'));

这是另一个演示(http://prepen.io/PiotrBerebecki/pen/dpVXyb),展示了使用1)jQuery和2)Axios库实现此目的的两种方法。

完整代码:

class App extends React.Component {  constructor() {    super();    this.state = {      time1: '',      time2: ''    };  }  componentDidMount() {    axios.get(this.props.url)      .then(response => {        this.setState({time1: response.data.time});      })      .catch(function (error) {        console.log(error);      });    $.get(this.props.url)      .then(result => {        this.setState({time2: result.time});      })      .catch(error => {        console.log(error);      });  }  render() {    return (      <div>        <p>Time via axios: {this.state.time1}</p>        <p>Time via jquery: {this.state.time2}</p>      </div>    );  }};ReactDOM.render(  <App url={"http://date.jsontest.com/"} />,  document.getElementById('content'));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649839.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号