React native 使用textInput React Native更新处于状态的数组对象中的元素
我在这里尝试使用textInput更新数组对象“available”,下面是我的代码。我不知道为什么它总是在更新函数行给我令牌错误。请帮忙。谢谢大家!React native 使用textInput React Native更新处于状态的数组对象中的元素,react-native,textinput,React Native,Textinput,我在这里尝试使用textInput更新数组对象“available”,下面是我的代码。我不知道为什么它总是在更新函数行给我令牌错误。请帮忙。谢谢大家! export class Inventory extends Component { state = { available: [ {id: 0, name: 'Xb', value:5}, {id: 1, name: 'Ad', value:19}, {id: 2, name: 'Sc',
export class Inventory extends Component {
state = {
available: [
{id: 0, name: 'Xb', value:5},
{id: 1, name: 'Ad', value:19},
{id: 2, name: 'Sc', value:1},
{id: 3, name: 'AV', value:3},
{id: 4, name: 'Ba', value:8},
{id: 5, name: 'Ch', value:2},
{id: 6, name: 'Pr', value:9},
{id: 7, name: 'Mi', value:10},
{id: 8, name: 'Se', value:1},
],
}
_update = (text,index) => this.setState({available[index].value: text});
render(){
index = 0;
return(
<View style={styles.container}>
<TextInput style={styles.input}
keyboardType = 'number-pad'
returnKeyType = 'go'
autoCapitalize = 'none'
maxLength = {3}
value = {this.state.available[index].value}
onChange = {(text) => _update(text,index)} />
</View>
);
}
导出类库存扩展组件{
状态={
提供:[
{id:0,名称:'Xb',值:5},
{id:1,名称:'Ad',值:19},
{id:2,名称:'Sc',值:1},
{id:3,名称:'AV',值:3},
{id:4,名称:'Ba',值:8},
{id:5,名称:'Ch',值:2},
{id:6,名称:'Pr',值:9},
{id:7,名称:'Mi',值:10},
{id:8,名称:'Se',值:1},
],
}
_update=(text,index)=>this.setState({available[index].value:text});
render(){
指数=0;
返回(
_更新(文本、索引)}/>
);
}
\u update=(text,index)=>this.setState({available[index].value:text})代码>在某些方面无效。首先,setState
获取一个对象,如果您正在更新该值,该对象应与当前状态中的键和值相同。其次,available[index]。由于未定义available
,因此值
不会计算为任何值。您只能通过this.state.available
访问available
。第三,available[index].value
将是新组件状态的关键,我想这不是您想要的
将您的更新更改为类似以下内容
_update = (text, index) => {
const newArray = [...this.state.available];
newArray[index].value = text;
this.setState({ available: newArray });
}
永远不要像直接使用普通javascript方式那样修改this.state。实际上,您应该记住,this.state是不可变的。最好的方法是:
1-首先创建状态数组的副本
2-查找项目的索引(如果索引可用,则跳过此索引)
3-更新该索引项的值
4-使用setState更新状态值。
因此,在您的情况下,您可以执行以下操作:
(text,index) => {
let newArray = [...this.state.available];
newArray[index] = {...newArray[index], value: text}
this.setState({available: newArray});
}
希望这对您有所帮助。谢谢您的回复。什么是..
称为扩展运算符的[…this.state.available]
。请检查此项以供参考。基本上,对于数组,一个spread操作符获取数组中的项,并将它们放入我们正在创建的新数组中。我尝试相同的方法,但它说不能在写事务之外修改托管对象。。。我正在处理react native和realm数据库以填充该数组。请尝试遵循realm文档并将用于填充数组的代码包装到“realm.write(()=>{…})”块中