这里是我的问题,如果我将已设置为Array项(array [0])的状态项更新为该Array(array [1])中的另一项,并且还有其他要引用的状态项该数组,应该知道其他状态项需要更新吗?
如果是,那么为什么我的下面的测试不起作用:
Class Decking extends React.Component {
constructor(props) {
super(props)
this.state = {
firstOption: props.product.acf.options.product_option[0],
title: props.product.title,
}
this.state.product = {
mainImage: {
url: this.state.firstOption.image_gallery[0].source_url,
alt: this.state.firstOption.image_gallery[0].alt_text,
},
thumbnails: this.state.firstOption.image_gallery,
price: this.state.firstOption.price,
dimensions: this.state.firstOption.dimensions,
options: props.product.acf.options.product_option,
desc: this.state.firstOption.description,
spec: this.state.firstOption.size___length_spec
}
}
toggleOptions(id) {
const option = this.state.product.options[id]
this.setState({firstOption: option})
}
render() {
return (
<div>
<div className="flex flex-wrap">
<div className="w-1/2">
<img className="w-full shadow-xl" alt={this.state.product.mainImage.alt} src={this.state.product.mainImage.url} />
<div className="-ml-2">
{this.state.product.thumbnails.map((thumbnail, index) => (
<img className="w-16 border-solid border-3 border-blue-400 mx-2" key={index} src={thumbnail.source_url} alt={thumbnail.alt_text} />
))}
</div>
</div>
<div className="w-1/2 pl-8">
<h1 className="text-4xl leading-normal">{this.state.title}</h1>
<div className="flex flex-wrap justify-between text-2xl mb-6">
<div className="font-light">
{this.state.product.dimensions}
</div>
<div className="font-light">
<b>Price:</b> {this.state.product.price}
</div>
</div>
<span className="text-xl font-light mb-4 block">Avaliable Options:</span>
<div className="flex flex-wrap mb-6 lg:mb-0">
{this.state.product.options.map((option, i) => (
<div className="w-full border-solid border-1 border-blue-400 shadow-lg flex items-center mb-4 px-5 py-4" key={i}>
<input onChange={e=>this.toggleOptions(e.target.id)} id={i} type="radio" /> <p className="checkChange mb-0 pl-4">{option.profileoption}</p>
</div>
))}
</div>
<div className="w-full nomargin mb-4">
<b className="text-xl">Desc:</b>
<div dangerouslySetInnerHTML={{__html: this.state.product.desc}} />
</div>
<div className="w-full nomargin">
<b className="text-xl">Spec:</b>
<div dangerouslySetInnerHTML={{__html: this.state.product.spec}} />
</div>
</div>
</div>
</div>
)
}
}
我已将this.state.firstOption
设置为数组项props.product.acf.options.product_option[0]
当我的toggleOptions
方法被调用时,该项会改变:
toggleOptions(id) {
const option = this.state.product.options[id]
this.setState({firstOption: option})
}
这里是该方法的调用位置:
<div>
{this.state.product.options.map((option, i) => (
<div key={i}>
<input onChange={e=>this.toggleOptions(e.target.id)} id={i} type="radio" /> <p>{option.profileoption}</p>
</div>
))}
</div>
我希望我已经阐明了我的问题,感谢您的关注:)