javascript - 为什么这两个函数更新 React 组件的方式不同?

标签 javascript reactjs

为什么 updateCardContentsBuggy() 不起作用?

如果我使用 updateCardContentsBuggy(),则 render() 永远不会使用新值。这是一些日志。正如您所看到的,当我从 render()

调用它时,title 永远不会有新值

Logs for updateCardContentsBuggy()

但是,如果我使用 updateCardContents()render() 将使用新值。日志显示 render() 获取新的状态值。

Logs for updateCardContents()

这是我的代码:

import React from 'react';
import './css/main.css';
import './css/w3.css';
import CardHTMLTemplate from './models/CardHTMLTemplate.js';

var axios = require('axios');

class CardClient extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            _id: null,
            title: "",
            description: "",
            tags: "",
            createdById: 0,
            createdAt: "",
            updatedAt: "",
            urgency: 50,
            isNew: false
        }

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.updateCardContents = this.updateCardContents.bind(this);
        this.updateCardContentsBuggy = this.updateContentsBuggy.bind(this);
    }

    updateCardContents(newCard) {
        this.setState({
            description: newCard["description"],
            title: newCard["title"],
            urgency: newCard["urgency"]
        });

    }

    updateCardContentsBuggy(newCard) {
        Object.keys(newCard).forEach(key => {
            this.setState({
            key: newCard[key]
            }, function() {
                console.log("Updated:" + key + " --> " + this.state.key + "\n");
            });
        });
    }

    componentDidMount() {
        axios.get('/read-card', {
            params: {
                _id: null
            }
        })
        .then((response) => {
            var card = response["data"][0];
            this.updateCardContents(card);
            // this.updateCardContentsBuggy(card);
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    handleInputChange(event) {
        this.setState({
            [event.target.name]: event.target.value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
    }

    render() {
        console.log("render() title = " + this.state.title);
        return (
            <CardHTMLTemplate 
                title={this.state.title}
                description={this.state.description}
                handleInputChange={this.handleInputChange}
                urgency={this.state.urgency}
                handleSubmit={this.handleSubmit}
            />        
        )
    }
}

export default CardClient;

最佳答案

您正在更新 updateCardContentsBuggy 中的 key,而不是 [key]。我想你想要:

updateCardContentsBuggy(newCard) {
    Object.keys(newCard).forEach(key => {
        this.setState({
        [key]: newCard[key]
        }, function() {
            console.log("Updated:" + key + " --> " + this.state.key + "\n");
        });
    });
}

关于javascript - 为什么这两个函数更新 React 组件的方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48588225/

相关文章:

javascript - 如何在子 React 组件中调用父方法?

javascript - React.JS 无法读取数组循环中的属性

javascript - && 评估问题

javascript - 试图从 javascript map 结果中隐藏 "undefined"

javascript - 解析页面当前项后执行 "Load more products"

javascript - React Hooks 状态变量在 setTimeout 函数期间未更新

reactjs - 在 React Material-UI DataGrid 中获取复选框选择上的行项目

javascript - 从 API 获取数据到状态

javascript - 将数值转换为字符串

javascript - 首先隐藏然后使用 jQuery 根据下拉选择显示多个 tbody 组