這段代碼有什麼內在的錯誤嗎?setState()不觸發重新渲染
部分的問題是這樣的:
// Update state and trigger re-render
// NOT WORKING
this.setState({ subsections });
國家沒有被置位,當我打電話的setState()。儘管數據存在於subsections
對象中。我在其他方法上使用了相同的代碼模式,並按預期工作。
數據也保存在Parse中,如果我刷新它的頁面。
import React from "react";
import Parse from 'parse';
import Subsections from './Subsections';
import AddSubsectionForm from './AddSubsectionForm';
class Manage extends React.Component {
constructor() {
super();
this.addSubsection = this.addSubsection.bind(this);
// Set initial state
this.state = {
subsections: {}
};
}
addSubsection(subsection) {
// Make copy of state
const subsections = {...this.state.subsections};
// Create new object
var SubsectionTest = Parse.Object.extend('SubsectionTest');
var subsectionTest = new SubsectionTest();
// Save object, then update state on return
subsectionTest.save({
name: subsection.name,
description: subsection.description
}).then(function(newSubsection) {
console.log('Has saved id of: '+newSubsection.id);
// Add new subsection to local state
subsections[newSubsection.id] = subsection;
// Log updatd subsections object
console.log(subsections);
// Update state and trigger re-render
// NOT WORKING
this.setState({ subsections });
},
function(error) {
console.log('Error:');
console.log(error);
});
}
/*
Loads subsections from Parse and displays them.
Code removed for clarity.
*/
componentWillMount() {
this.loadMenuItems();
}
render() {
if (this.state.subsections) {
return (
<div className="subsections">
<div className="mt3 border-top">
<h3 className="mt1 bold s2">Subsections</h3>
<div className="mt1">
<Subsections subsections={this.state.subsections} />
</div>
</div>
<div className="mt3 border-top">
<AddSubsectionForm addSubsection={this.addSubsection}/>
</div>
</div>
)
}
}
}
export default Manage;
你應該'else {return null; }'在你的render()函數中(不是答案,我知道它只是伸出在我身上) – rossipedia