Javascript 如何在索引中设置数组的状态?自然反应
我在该州拥有一个数组:Javascript 如何在索引中设置数组的状态?自然反应,javascript,react-native,Javascript,React Native,我在该州拥有一个数组: constructor() { super(); this.state = { title: "", content: ["",""], note_number: "", fetch_notes: "", img: "", } } 因此,我在这里设
constructor() {
super();
this.state = {
title: "",
content: ["",""],
note_number: "",
fetch_notes: "",
img: "",
}
}
因此,我在这里设置数组的值:
const {params} = this.props.navigation.state;
this.setState({title: params.data.title});
let array_notes = this.state.content.slice();
array_notes[0] = params.data.content;
this.setState({content: array_notes});
this.setState({note_number: params.note_number});
this.setState({fetch_notes: params.fetch_notes});
如您所见,我使用slice方法创建了一个新变量,这将创建原始数组的副本,使用索引0,我告诉他在该索引中存储内容(字符串)插入内容,问题是在这里,我在索引1中打印数组,该数组应为空,但它得到的值与索引0相同,我认为这是因为方法onchangetext,即:
<View style = {this.styles.textinput_container}>
<TextInput style = {this.styles.TextInput_title} placeholder = "Title" multiline = {true} maxLength = {80} value = {this.state.title} onChangeText = {title => this.setState({title: title})}></TextInput>
<TextInput placeholder = "Content" multiline = {true} value = {this.state.content[0]} onChangeText = {text => this.setState(({content:[text,this.state.content[0]]}))}></TextInput>
<Text>{this.state.content[1]}</Text>
</View>
我真的不太理解这个代码,因为有人把它传给了我,但它应该只存储在零的位置,为什么我在打印它的时候呢
<Text>{this.state.content[1]</Text>
{this.state.content[1]
索引1得到的值与函数中的零相同
text => this.setState(({ content: [text, this.state.content[0]] }));
将设置this.state.content
设置为数组,其中第0个索引等于text
,第1个索引等于this.state.content[0]
,即之前第0个索引中的内容
如果希望数组只有一个值,即第0个索引,则可以执行以下操作
text=>this.setState(({content:[text]]}));
如果希望text
替换this.state.content
的第0个索引,可以执行以下操作
text=>this.setState(state=>({content:[text,…state.content.slice(1)]]);
编辑:
如果要更新任意索引,可以创建一个通用的更新函数,如下所示
const setIndex=(VAL,i,v)=>[
…VAL.切片(0,i),
v
…VAL.切片(i+1)
];
像这样使用它
text=>this.setState(state=>({content:setIndex(state.content,0,text)}));
ok,谢谢,,但这是第一个索引:text=>this.setState(({content:[text]]}));如果我想设置第二个索引呢?我已经添加了一个示例,可以用来更新任何索引。虽然我个人认为这不是一个好方法。
text => this.setState(({ content: [text, this.state.content[0]] }));