jquery - 如何保存 jQuery Get 响应到 React 变量?

标签 jquery reactjs

如何将 $.get() 中的 response.status 保存到 React 变量 this.posts 中?

当我尝试从 $.get() 中访问 this.posts 时,它返回 undefined

import React, { Component } from 'react';
import $ from 'jquery';

class MediumPosts extends Component {

  constructor(props) {
    super(props);
    this.posts = [];
  }

  fetchPosts = () => {
    var data = {
      rss_url: 'https://medium.com/feed/tradecraft-traction'
    };
    $.get('https://api.rss2json.com/v1/api.json', data, (response) => {
      if (response.status == 'ok') {
        console.log(response.items);
        this.posts = response.items; // Undefined
      }
    });
  }

  componentDidMount() {
    this.fetchPosts();
  }

  render() {
    return (
      <ul>
        {this.posts.map(function(item, i) {
          return (
            <li key={item.guid}>
              <h4>{item.title}</h4>
              <time>{item.pubDate}</time>
            </li>
          )
        })}
      </ul>
    )
  }
}

export default MediumPosts;

最佳答案

基本上,您应该保持您的帖子处于状态。

当值随时间变化时,它应该处于状态(如果它不是来自父组件),然后您只需更新它。

ReactJS docs reference

因此,您的代码将如下所示:

class MediumPosts extends Component {

  constructor(props) {
    super(props);

    // init state
    this.state = {
        posts: [],
    }
  }

  fetchPosts = () => {
    // because you are pass arrow function in the callback we have to save `this`.
    // or you can create callback function in the component and pass it
    const self = this;
    const data = {
      rss_url: 'https://medium.com/feed/tradecraft-traction'
    };

    $.get('https://api.rss2json.com/v1/api.json', data, response => {
      if (response.status == 'ok') {
        self.setState({posts: response.items});
      }
    });
  }

  componentDidMount() {
    this.fetchPosts();
  }

  render() {
    return (
      <ul>
        {this.state.posts.map(function(item, i) {
          return (
            <li key={item.guid}>
              <h4>{item.title}</h4>
              <time>{item.pubDate}</time>
            </li>
          )
        })}
      </ul>
    )
  }
}

export default MediumPosts;

无论如何,我建议你在 ReactJS 项目中摆脱 jQuery 。相反,使用 axios .

希望对您有所帮助。

关于jquery - 如何保存 jQuery Get 响应到 React 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49420637/

相关文章:

javascript - 链接同步 Redux 操作并在组件中消费

reactjs - Antd 表单远程提交

javascript - React - 在 api 调用之前填充数据?

javascript - 如何获取带有名称的选择框值

jquery - 更改 jQuery 验证插件错误消息的位置?

javascript - 如何在 html 和 javascript 中制作多个 url opener

reactjs - react native : Passing props between components and componentWillMount() method

javascript - 在 redux 中,reducer 改变状态后会发生什么?

javascript - 如何让 BlueImp jQuery FileUpload 生成唯一的文件名

javascript - 计算 .load 上的两个持久引导选择值