为什么updateCardContentsBuggy()
无效?
如果我使用updateCardContentsBuggy()
,则render()
从不使用新值。这是一些日志。如您所见,title
从render()
但是,如果我使用updateCardContents()
,则render()
会使用新值。日志显示render()
获取新的状态值。
这是我的代码:
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;
答案 0 :(得分:3)
您正在key
更新[key]
而不是updateCardContentsBuggy
。我想你想要:
updateCardContentsBuggy(newCard) {
Object.keys(newCard).forEach(key => {
this.setState({
[key]: newCard[key]
}, function() {
console.log("Updated:" + key + " --> " + this.state.key + "\n");
});
});
}