【问题标题】:Array.length says it's 0 even when it's not React/Javascript/TypescriptArray.length 说它是 0,即使它不是 React/Javascript/Typescript
【发布时间】:2020-11-25 18:35:46
【问题描述】:

我正在尝试使用 electron-json-storage 为电子应用程序存储持久数据,我尝试使用 neDB,但它会抛出此错误,所以我切换了,但它看起来不是 neDB 的问题,而是我自己的问题。

这是问题所在:我正在尝试从存储中获取信息,当我调用相应的 get 方法并将信息输出到控制台时,Getmethod 中的一切似乎都很好,当我执行控制台时,一切似乎都很好.log(Get()) 但一旦我尝试映射它或获取返回数组的长度,它就会认为该数组为空。

这是我的代码:

import * as React from "react";
import { Component } from "react";
import { ToastContainer } from "react-toastify";
import { connect } from "react-redux";
import GetAllCharacters from "../../scripts/GetAllCharacters";
const mapStateToProps = (state) => {
    return {
        character: state,
    };
};

const mapDispatchToProps = (dispatch) => ({});

const Sheet = (props) => {
    const [characters, setCharacters] = React.useState();
    return (
        <div className="container-fluid">
            <div className="row" style={{ marginRight: "0px" }}>
                {props.character != null ? (
                    <>
                        //Code Removed for irrelevancy
                    </>
                ) : (
                    <>
                    {console.log(GetAllCharacters()}<--prints an array of characters to the console
                    {GetAllCharacters().length}</><--returns 0 despite the fact it just printed the characters to the console
                )}
            </div>
        </div>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(Sheet);

GetAllCharacters()

import { Character } from "../Data/Character";

function GetAllCharacters() {
    var returnCharacters: Character[] = [];
    const storage = require("electron-json-storage");

    storage.getAll(function (error, data) {
        if (error) throw error;
        Object.entries(data).map((c) => {
            returnCharacters.push(<Character>c[1]);
        });
    });
    console.log(returnCharacters);
    return returnCharacters;
}
export default GetAllCharacters;

【问题讨论】:

  • 你能试试[...GetAllCharacters()].length() 吗?
  • " - 不,它将打印一个空数组([ ] 中没有任何元素)。只有在控制台中展开它后,您才会看到元素并且.length 将非零。试试console.log(JSON.stringify(GetAllCharacters())},你只会得到一个空数组。
  • 在这种情况下你会缝什么:console.log(Array.isArray(Get()))
  • 如果您对Array.prototype.map() 的返回值不感兴趣,那么.map() 是错误的方法。使用.forEach() 或重构您的函数。

标签: javascript reactjs electron


【解决方案1】:

GetAllCharacters 应该是一个异步函数(因为它会获取一些async 数据)。 GetAllCharacters().length 将始终为 0,因为 GetAllCharacters() 返回一个空数组。

function GetAllCharacters() {
    var returnCharacters: Character[] = [];
    const storage = require("electron-json-storage");
    // ** HERE IS THE PROBLEM ** This is async. and the next line will get runned instantly and donesn't wait for it to get the data.
    storage.getAll(function (error, data) {
        if (error) throw error;
        Object.entries(data).map((c) => {
            returnCharacters.push(<Character>c[1]);
        });
    });
    // ** Now returnCharacters is empty array, and it will return it.
    console.log(returnCharacters);
    return returnCharacters;
}

您应该更正您的GetAllCharacters 函数以异步获取所有结果,并在最后返回结果数组(例如callback)。然后你应该在你的组件中调用GetAllCharacters(result =&gt; {setCharacters(result)}),例如useEffect,然后绑定characters来渲染。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2016-08-26
    • 1970-01-01
    • 2014-01-09
    • 2019-02-08
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多