【发布时间】:2017-05-15 02:46:07
【问题描述】:
我正在尝试使用 React,我遇到了更新特定键的状态值的问题。
这是我的状态
this.state = {
connections : {
facebook : "http://facebook.com",
flickr : null,
foursquare : null,
googleplus : null,
id : 0,
instagram : "http://instagram.com/",
openstreetmap : null,
pinterest : null,
place_id : 1,
tomtom : null,
tripadvisor : null,
twitter : "http://twitter.com",
vimeo : null,
wikipedia : null,
yelp : null,
youtube : null
},
contact : {
}
}
我正在调用一个外部组件并向它发送参数。
<Connection type="Facebook" icon={facebookIcon} placeholder="Add Facebook Link" name="facebook" value={this.state.connections.facebook} onChange={this.handleChange.bind(this)}/>
<Connection type="Twitter" icon={twitterIcon} placeholder="Add Twitter Link" name="twitter" value={this.state.connections.twitter} onChange={this.handleChange.bind(this)}/>
<Connection type="Instagram" icon={instagramIcon} placeholder="Add Instagram Link" name="instagram" value={this.state.connections.instagram} onChange={this.handleChange.bind(this)}/>
外部文件中的组件:
<input type="text" name={this.props.name} placeholder={this.state.placeholder} value={this.props.value} onChange={this.props.onChange} />
在文本框中更改值时,
handleChange(e) {
this.setState({
connections : {[e.target.name]: e.target.value}
})
}
当我尝试更改任何字段值时,它将其余 2 设置为空。例如,如果我尝试编辑 Facebook 的文本框,它会将 Twitter 和 Instagram 的值设置为空。
我可以知道我在设置 handleChange 时做错了什么吗?我确定 this.setState 有问题,但不确定如何定位特定的键值。
【问题讨论】:
-
首先,您不应该拥有如此长的本地状态列表。原因 a)难以管理 2)如果您尝试更改任何内容,它将破坏您的代码。将大组件分解成较小的组件。对于您的问题,请尝试在 handleChange 函数中添加 e.preventDefault
-
@KhalidAzam 谢谢你让我知道,我看不出有什么办法可以打破这个名单,你有什么建议吗?因为,我的下一个组件是便利设施,它的列表是这个列表的 100 倍。我想存储为外部 js 并在此处导入。任何更好的想法将不胜感激。
标签: javascript reactjs ecmascript-6 react-redux