React Flux 通过 API 调用加载初始数据

IT技术 javascript reactjs reactjs-flux
2021-05-20 06:55:01

我已经被这个问题困了几个小时了。我想实现 Flux 架构。我正在尝试创建一个待办事项列表。但是,我想事先加载一些初始数据。例如在我的 todoStore.js 中:

import { EventEmitter } from "events";

class ToDoStore extends EventEmitter {
    constructor(){
        super();
        this.bucket_list = [{
            id: 123,
            name: "Hi",
            isCompleted: false
        }]

    }

    getAll(){
        return this.bucket_list;
    }
}

我这里有一些初始数据,供我的todo.js

import toDoStore from './stores/todoStore'

class BucketApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bucket_list: toDoStore.getAll()
        };
    }

这很好用。我有一个商店,它基本上是collectioncomponent从中接收数据的商店但是,现在我想从数据库中初始化数据。所以我更新了我的todoStore.js

class BucketlistStore extends EventEmitter {
    constructor(){
        super();
        fetch(url)
            .then(d => d.json())
            .then(d => {
                this.bucket_list = d;
            });
    }

    getAll(){
        return this.bucket_list;
    }
}

但是, getAll() 返回undefined. 为什么会这样?我究竟做错了什么?

4个回答

它返回undefined是因为获取数据是异步的并且在初始化期间this.bucket_list未定义。试试这个:

class BucketlistStore extends EventEmitter {
    constructor(){
        super();
        this.bucket_list_promise = fetch(url)
            .then(d => d.json());
    }

    getAll(){
        return this.bucket_list_promise;
    }
}

然后

import toDoStore from './stores/todoStore'

class BucketApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loadingData: true,
            bucket_list: null
        };
    }

    componentWillMount(){
       toDoStore.getAll().then(result => {
          this.setState({ bucket_list: result, loadingData: false }) 
       })
    }

既然fetch是异步操作,可能你调用getAll()太早了?这不是解决方案,但您可以检查假设:

class BucketlistStore extends EventEmitter {
    constructor(){
        super();
        this.loading = true;
        fetch(url)
            .then(d => d.json())
            .then(d => {
                this.loading = false;
                this.bucket_list = d;
            });
    }

    getAll(){
        console.log(this.loading);
        return this.bucket_list;
    }
}

如果是真的,我建议不要渲染BucketAppwhile loadingis true放置标志以存储并使用它BucketApp来防止渲染(改为显示加载器)。

我想这是因为您的组件在结束异步获取之前呈现自身。换句话说,您得到未定义,并且当您在完成后fetch(当您的商店更新时)获得结果时,您的组件不会更新。您可以应用上述技术,也可以使用 Redux。在 Redux 中,如果 store 被更新,它会导致以某种方式与 Redux store 连接的所有组件的更新。

为了解决这个问题,我加载了组件状态的初始数据,并在Promise解决时监听 componentDidMount 上的发射以更新状态。下面是您的代码示例。

//店铺

import EventEmitter from "events";
let initState = {
  id: 123,
  name: "Hi",
  isCompleted: false,
  loadingData: true
};

class BucketlistStore extends EventEmitter {
  constructor() {
    super();
    fetch(url)
      .then(d => d.json())
      .then(d => {
        const { id, name, isCompleted } = d;
        initState = { id, name, isCompleted, loadingData: false };
        this.emit("updated");
      });
  }

  getAll() {
    return initState;
  }
}

export default new BucketlistStore();

//零件

import React, { Component } from "react";
import toDoStore from "./stores/todoStore";

class BucketApp extends Component {
  constructor(props) {
    super(props);
    this.state = toDoStore.getAll();
  }

  updateState = () => {
    const { id, name, isCompleted, loadingData } = toDoStore.getAll();
    this.setState({ id, name, isCompleted, loadingData });
  };

  componentWillMount() {
    toDoStore.on("updated", this.updateState);
  }

  componentWillUnmount(){
    toDoStore.off("updated", this.updateState);
  }

  render() {
    const { id, name, isCompleted, loadingData } = this.state;

    if (loadingData) return <p>Loading...</p>;

    return null; //your code
  }
}