【发布时间】:2014-12-21 23:47:14
【问题描述】:
假设有一个用 react.js 编写的应用程序。它通过 rest api 获取单个 json 并将一些属性传递给子组件。
什么是处理可能缺少的 json 属性和东西的正确方法?如果有道具,我可能应该检查每个组件,并用适当的结构填充状态但填充空数据,如下所示:
var SomeComponent = React.createClass({
getInitialState: function() {
return {
someNestedStructure: {
foo: {
bar: null,
baz: null
},
morenested: {
something: '',
andEvenMoreNested: {
somethingb: ''
}
},
somedata: {
id: null
},
somedataaa: {
}
}
}
},
componentDidMount: function() {
//call rest api and set new state depending on what is inside json
//check every required field to pass to children compoents
},
render: function() {
return (
<div>
<ComponentUsingNEsteStructure data={this.state.someNestedStructure.moreNested}/>
<ComponentThatNeedsEverythign data={this.state.someNestedStructure} />
<SomeOtherComponent some={this.sate.somedataaa} />
</div>
);
}
});
但我猜它会在代码中生成很多与 json 相关的结构和很多 if。
感谢您的帮助!
【问题讨论】:
标签: javascript json rest design-patterns reactjs