【发布时间】:2019-06-06 11:14:32
【问题描述】:
state 对象中有一个空白数组。该数组将包含一些具有键值对的对象。
这是我的代码:
import * as React from 'react';
import { Text, ScrollView, View, StyleSheet, TouchableOpacity, TextInput, ListView, Switch, Button } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
constructor(props){
super(props);
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
TodoTextVal: '',
todos: []
}
this.addTodo = this.addTodo.bind(this);
}
addTodo() {
id++;
let TodoTextVal = this.state.TodoTextVal;
//let arrVal = {id: id, text: TodoTextVal, checked: false}
//this.setState(prevState => ({todos : [...prevState.todos, arrVal]}));
this.setState({
todos: [
...this.state.todos,
{id: id, text: TodoTextVal, checked: false}
],
})
}
toggle(id) {
}
render() {
return (
<View style={styles.container}>
<View style={{flexDirection: "row"}}>
<TextInput
onChangeText={(TodoTextVal) => this.setState({TodoTextVal})}
ref= {(el) => { this.TodoTextVal = el; }}
style={[styles.input, {flex: 2} ]}
placeholder="Add Todo..."/>
<TouchableOpacity onPress={this.addTodo} title="+ Add" style={styles.button} >
<Text>Add</Text>
</TouchableOpacity>
</View>
<ListView
dataSource={this.ds.cloneWithRows(this.state.todos)}
renderRow={(data) => <View><Text>{data}</Text></View>} />
</View>
);
}
}
let id = 0
这里的问题是this.setState() 没有更新状态。我已经尝试了您在addTodo() 中看到的注释代码的方法。
但是这两种方法都抛出了一条错误消息:
设备:(96:380) 不变违规:对象作为 React 无效 孩子(找到:带有键 {id、text、checked} 的对象)。
【问题讨论】:
-
你是如何使用
todos数组的,你能分享一些代码吗? -
不,我还没有使用它。在更新之前如何使用它?首先我想设置状态。
-
请分享
render方法的代码 -
您提供的错误主要与您如何渲染组件有关,如果您可以分享它会很好
-
我已经更新了我的代码。请立即查看
标签: javascript reactjs react-native state setstate