gpt4 book ai didi

javascript - 使用 Parse Server 返回的数据更新状态后,无法让 React 组件重新渲染

转载 作者:行者123 更新时间:2023-12-03 04:34:59 26 4
gpt4 key购买 nike

我在使用状态数据渲染组件时遇到问题。我从 Parse Server 提取数据,然后用该数据更新状态。但是,我使用该数据的组件(下面代码中的 <MenuItem /> )在数据可用之前就已渲染。

我尝试了这里描述的方法: How to wait for AJAX response and only after that render the component?

但我无法让组件识别正在更新然后重新渲染的状态。

有什么想法吗?完整代码如下。还附上一张屏幕截图,显示成功的控制台日志以及状态数据的存在。

(应该注意的是,我是 React 新手,所以很多代码可能不是最佳的。)

import React from "react";
import Parse from 'parse';

import MenuItem from './MenuItem';

class MenuItems extends React.Component {
constructor() {
super();

this.loadMenuItems = this.loadMenuItems.bind(this);

this.state = {
menuItems: {},
order: {}
};
}

loadMenuItems() {
/* 0a. Get copy of State? */
const menuItems = {...this.state.menuItems};

/* 0. Get User */
// TODO: Get this from props
var user = Parse.User.current();

/* 1. Get Menu Items for this user */
var MenuItemTest = Parse.Object.extend('MenuItemTest');
var query = new Parse.Query(MenuItemTest);

query.equalTo('user', user);
query.find({
success: function(returnedMenuItems) {
console.log("Successfully retrieved " + returnedMenuItems.length + " menu items.");

for (var i = 0; i < returnedMenuItems.length; i++) {
var object = returnedMenuItems[i];

const menuItem = {
name: object.get('name'),
price: object.get('price'),
description: object.get('description'),
}

menuItems[`menu-item-${object.id}`] = menuItem;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});

this.setState({ menuItems });
}

componentWillReceiveProps(nextProps) {
console.log(nextProps);
this.loadMenuItems();
}

componentWillMount() {
this.loadMenuItems();
}

render() {
// Example from:
// https://stackoverflow.com/questions/31723095/how-to-wait-for-ajax-response-and-only-after-that-render-the-component

if (!this.state.response) {
return <div>Loading...</div>;
}

if (this.state.response.length === 0) {
return <div>No menu items yet</div>;
}

return (
<div className="menu-items">
{
Object
.keys(this.state.menuItems)
.map(key => <MenuItem key={key} details={this.state.menuItems[key]} />)
}
</div>
)
}
}

export default MenuItems;

Screenshot showing state with items

Successful console log

更新代码以与评论线程一致

import React from "react";
import Parse from 'parse';

import MenuItem from './MenuItem';

class MenuItems extends React.Component {
constructor() {
super();

this.loadMenuItems = this.loadMenuItems.bind(this);
}

loadMenuItems() {
const menuItems = {};

/* 0. Get User */
var user = Parse.User.current();

/* 1. Get Menu Items for this user */
var MenuItemTest = Parse.Object.extend('MenuItemTest');
var query = new Parse.Query(MenuItemTest);

query.equalTo('user', user);
query.find({
success: function(returnedMenuItems) {
console.log("Successfully retrieved " + returnedMenuItems.length + " menu items.");

for (var i = 0; i < returnedMenuItems.length; i++) {
var object = returnedMenuItems[i];

const menuItem = {
name: object.get('name'),
price: object.get('price'),
label: object.get('label'),
shorthand: object.get('shorthand'),
description: object.get('description')
}

menuItems[`menu-item-${object.id}`] = menuItem;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});

this.setState({ menuItems });
}

componentWillReceiveProps(nextProps) {
console.log('I ran');
console.log(nextProps);
this.loadMenuItems();
}

componentWillMount() {
this.loadMenuItems();
}

render() {
// Handle case where the response is not here yet
if (!this.state.menuItems) {
console.log('No state');
return <div>Loading...</div>;
}

// Gives you the opportunity to handle the case where the ajax request
// completed but the result array is empty
if (this.state.menuItems.length === 0) {
console.log('Zero items');
return <div>No menu items yet</div>;
}

if (this.state.menuItems) {
return (
<div className="menu-items">
{ console.log(this.state.menuItems) }
{ console.log(Object.keys(this.state.menuItems)) }
</div>
)
}
}
}

export default MenuItems;

最佳答案

据我从你这里得到的信息来看,

if (!this.state.response) {
return <div>Loading...</div>;
}

if (this.state.response.length === 0) {
return <div>No menu items yet</div>;
}

this.state.response 从未在状态中设置,因此将始终显示正在加载...

我相信您想将其更改为

if (!this.state.menuItems) {
return <div>Loading...</div>;
}

if (this.state.menuItems.length === 0) {
return <div>No menu items yet</div>;
}

并且您的构造函数根本不将menuItems设置为状态(因此最初会显示加载)。

关于javascript - 使用 Parse Server 返回的数据更新状态后,无法让 React 组件重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43332870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com