【问题标题】:How to persist data in react component from re-render?如何从重新渲染中将数据保留在反应组件中?
【发布时间】:2020-02-25 10:19:19
【问题描述】:

我正在对 nodejs 服务器进行简单的 axios 调用,以响应从 mongoose 模式模型中获取产品。当我第一次加载页面时,我使用 componentDidMount 从 MongoDB 获取现有产品。但是,当我刷新页面时,所有项目都消失了。

反应组件(componentDidMount):


class Product extends Component {
  constructor(props) {
    super(props);
    this.state = { products: '' };
  }

componentDidMount() {

  axios.get('http://localhost:3001/getProduct')
    .then(res => {
       this.setState({ products: res.data });
      }).catch((err) => {
        console.log(err);
      });
  }

Nodejs 服务器(/getProduct api):

app.get('/getProduct', (req,res) => {

   Products.find(product_id), (err, products) => {
       if(err) throw err;
       res.status(200).send(products);
   });
}

我相信这与回调有关?请帮忙,我是新手。

【问题讨论】:

  • 您是在 componentDidMount 中创建组件吗?
  • 对不起;错字。固定
  • @jche 如果你想永久保存,那么可以使用 localstorage 或 sessionStorage 因为每次重新加载页面后都会调用 api。
  • 对不起,我的意思是刷新页面,而不是重新加载。
  • 这是从 localStorage stackoverflow.com/a/58620458/6544460 保存和获取数据的正确方法。

标签: node.js reactjs callback axios react-component


【解决方案1】:

如果您正在使用小型反应应用程序(没有 redux),那么您必须使用 localStoragesessionStorage 来保存数据。看下面的例子。

class Product extends Component {
  constructor(props) {
    super(props);
    // get product list from localstorage
    this.state = { products: localStorage.getItem('productList') ? JSON.parse(localStorage.getItem('productList')) : [] };
  }

componentDidMount() {
  axios.get('http://localhost:3001/getProduct')
    .then(res => {
       this.setState({ products: res.data }, ()=>{
            // set product list in localstorage
            localStorage.setItem('productList', JSON.stringify(res.data));
         });
      }).catch((err) => {
        console.log(err);
      });
}

【讨论】:

  • 由于您使用axios w/c 自动转换为JSON,您需要先stringify 存储数据,然后parsegetting 时将其转换为JSON。
【解决方案2】:
class Product extends React.Component {
  constructor(props) {
    super(props);
    // get product list from localstorage
    this.state = {
      products: JSON.parse(localStorage.getItem("products")) || []
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:3001/getProduct") // https://jsonplaceholder.typicode.com/posts
      .then(res => {
        this.setState({ products: res.data }, () => {
          // set product list in localstorage
          localStorage.setItem("products", JSON.stringify(res.data));
        });
      })
      .catch(err => {
        console.log(err);
      });
  }
  render() {
    const { products } = this.state;
    return (
      <div>
        {products
          ? products.map(product => <div key={product.id}>{product.title}</div>)
          : null}
      </div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2022-01-02
    相关资源
    最近更新 更多