gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:38:15 26 4
gpt4 key购买 nike

为什么 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/

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