【发布时间】:2017-08-14 22:16:34
【问题描述】:
我刚开始学习 react,但在尝试更新单个 <Option /> 子元素的状态时遇到了麻烦。
我的 Flux Store 正在发出变化,在 React devtools 中我可以看到 StyleOptions 元素的状态正在更新,但它不会更新子组件<Option />。
我怀疑这是因为我将选项列表保存在一个变量中。
我需要使用这个,因为我从 JSON 中提取了这个选项。
const Options = this.state.options.map((parent) => {
const children = parent.children.map((child) => {
return (
<Option {...child} />
)
});
return <Option {...parent} children={children} />;
});
所以我认为这部分可能会导致问题。
我来自OptionsStore 的示例数据如下所示。
this.options = [
{
key: "suitType",
label: "Suit Type",
selected: false,
children: [
{
key: "suittype_skinny",
parent: "suitType",
label: "Skinny",
price: "£50",
description: "Short description",
images: {
general: "http://placehold.it/600x600",
closeUp: "http://placehold.it/620x620",
thumbnail: "http://placehold.it/100x100",
},
selected: false,
},
{
key: "suittype_wedding",
parent: "suitType",
label: "Wedding",
price: "£50",
description: "Short description",
images: {
general: "http://placehold.it/600x600",
closeUp: "http://placehold.it/620x620",
thumbnail: "http://placehold.it/100x100",
},
selected: false,
}
]
}
]
子道具也没有改变。
完整代码在这里:
import React, { Component } from 'react';
import Option from './Option';
import OptionsStore from '../../stores/OptionsStore';
class StyleOptions extends Component {
constructor(props) {
super(props)
this.state = {
options: OptionsStore.getAllItems(),
}
}
componentDidMount() {
OptionsStore.on('change',(e) => {
this.setState({
options: OptionsStore.getAllItems(),
});
console.log('optionsStore received an update');
});
}
render() {
const Options = this.state.options.map((parent) => {
const children = parent.children.map((child) => {
return (
<Option {...child} />
)
});
return <Option {...parent} children={children} />;
});
return(
<div className="col-xs-6">
<ul className="list-group">
{Options}
</ul>
</div>
)
}
}
export default StyleOptions;
还有<Option /> 代码:
import React, { Component } from 'react';
export default class Option extends Component {
constructor(props) {
super(props);
this.hasChildren = this.props.children ? true : false;
this.hasThumb = this.props.images ? true : false;
this.children = this.state.children;
this.state = {
label: this.props.label,
description: this.props.description,
selected: false,
price: this.props.price
}
}
render() {
return (
<li className={this.hasChildren ? 'list-group-item':'col-sm-4 list-group-item' } selected={this.state.selected}>
<a className="media">
{this.hasThumb ? (
<div className="media-left media-middle">
<img src={this.props.images.thumbnail} alt={this.state.label} />
</div>
) : (
' '
)}
<div className="media-body">
<h4 className="option-name">{this.state.label}</h4>
<p className="info">{this.state.description}</p>
<span className="text-success pricing">{this.state.price}</span>
</div>
</a>
{this.hasChildren ? (
<ul className="panel-body">
{this.children}
</ul>
) : (
' '
)}
</li>
)
}
}
希望有人能帮忙。
【问题讨论】:
标签: json reactjs ecmascript-6 flux reactjs-flux