在React中使用Axios和MobX从服务器获取数据

xvw2m8pv  于 2023-01-17  发布在  iOS
关注(0)|答案(1)|浏览(161)

我需要从服务器获取数据并将其保存在某个地方,以便在重新呈现LoginsList组件后,不必再次从服务器请求数据。我决定开始使用MobX,但似乎没有调用存储函数fetchData()。
目前,数据以原始形式被接受,但之后我将使用加密。
store.js

import { makeObservable } from 'mobx';

class store {
    data = []
    isFetching = false
    error = null

    constructor() {
        makeObservable(this, {
            data: observable,
            isFetching: observable,
            error: observable,
            fetchData: action
        })
    }

  fetchData() {
    this.isFetching = true
    axios.get('http://localhost:3001/data')
      .then(response => {
        this.data = response.data
        this.isFetching = false
        console.log('Success');
      })
      .catch(err => {
        this.error = err
        this.isFetching = false
        console.log('Error');
      })
  }
}

export default store;

LoginsList.js

import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import { Observer } from 'mobx-react-lite';
import store from '../.store/data';

import LoginDetails from './LoginDetails';
import Login_Icon from '../assets/icons/Login.svg'
import '../assets/css/LoginCards.css'

const LoginsList = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [hoveredTab, setHoveredTab] = useState(null);

  const handleMouseEnter = (index) => {
    if (index !== activeTab) {
        setHoveredTab(index);
    }
  }

  const handleClick = (index) => {
    setHoveredTab(null);
    setActiveTab(index);
  }

  useEffect(() => {
    store.fetchData();
  }, []);

  return (
    <>
    <Observer>
      <ul>
        {store.data.map((card, index) => (
          <li
            key={card.id} 
            onClick={() => handleClick(index)}
            onMouseEnter={() => handleMouseEnter(index)}
            onMouseLeave={() => setHoveredTab(null)}
            className="LoginCard"
          >
            <div
              className={classNames('LoginCardContainer', { 'active-logincard': index === activeTab }, { 'hovered-logincard': index === hoveredTab })}
            >
                <img src={Login_Icon} alt="Login Icon"></img>
                <div className="TextZone">
                    <p>{card.name}</p>
                    <div>{card.username}</div>
                </div>
            </div>
          </li>
        ))}
      </ul>
      <div>
        <div className="LoginDetails">
          <img className="LoginDetailsIcon" src={Login_Icon}></img>
        </div>
          <LoginDetails key={activeTab} name={store.data[activeTab].name} username={store.data[activeTab].username} password={store.data[activeTab].password}/>
          {store.data[activeTab].password} 
      </div>
      </Observer>
    </>

  );
}

export default LoginsList;

我尝试创建一个存储,将其导入LoginsList组件并获取数据。在浏览器控制台中,我看到错误Uncaught TypeError: _store_data__WEBPACK_IMPORTED_MODULE_3__.default.data is undefined
如果我在浏览器中打开http://localhost:3001/data,我可以很容易地读取数据。我认为错误不在服务器端。

disbfnqx

disbfnqx1#

我解决了这个问题。我所要做的就是使用makeAutoObservable而不是makeObservable。

import { action, makeAutoObservable } from 'mobx';
import axios from 'axios';

class UserData {
    data = []
    isFetching = false
    error = null

    constructor() {
        makeAutoObservable(this)
    }

  fetchData() {
    this.isFetching = true
    axios.get('http://localhost:3001/data')
      .then(response => {
        this.data = response.data
        this.isFetching = false
        console.log('Success');
      })
      .catch(err => {
        this.error = err
        this.isFetching = false
        console.log('Error');
      })
  };
}

export default new UserData;

相关问题