我在列表中显示了一系列对象,每个字段都有一些属性:objectID / key,weight,reps。我传递给更新函数的值不是在客户端上已修改的值,而是仍处于我的状态的值。我该如何从客户那里传递价值?
export const updateUserData = async (exerciceID, date, weight, reps) => {
let userID = firebase.auth().currentUser.uid
let ref = firebase.database().ref('users/' + userID + '/exercices/' + exerciceID)
ref.update({
'date': date,
'weight': weight,
'reps': reps
}).then((data) => {
console.log('data: ', data)
}).catch((error) => {
console.log('error: ', error)
})
}
updateData(exerciceID, date, weight, reps) {
updateUserData(exerciceID, date, weight, reps)
this.readData()
}
return (
<ScrollView>
{Object.entries(this.state.results).map(([key, value]) => {
console.log(key, value)
return (
<View key={key} style={styles.listContainer}>
<View style={styles.row}>
<TextInput style={styles.input} placeholder="Kg" keyboardType="number-pad">{JSON.stringify(value.weight)}</TextInput>
<TextInput style={styles.input} placeholder="reps" keyboardType="number-pad">{JSON.stringify(value.reps)}</TextInput>
<Button color='red' styles={styles.button} title="Update" onPress={() => this.updateData(key, value.date, value.weight, value.reps)}></Button>
<Button color='red' styles={styles.button} title="delete" onPress={() => this.deleteData(key)}></Button>
</View>
</View>
)
})
}
</ScrollView>
)
答案 0 :(得分:1)
您需要保存状态更改。像
state = {
kg: '',
reps: '',
}
在您的输入中添加onChage处理程序。
<TextInput onChangeText={(kg) => this.setState({kg})} style={styles.input} placeholder="Kg" keyboardType="number-pad" />
然后在updateData函数中,从state中获取这些值并更新数据。
updateData(exerciceID, date) {
const { kg, reps } = this.state;
updateUserData(exerciceID, date, kg, reps)
this.readData()
}
<View key={key} style={styles.listContainer}>
<View style={styles.row}>
<TextInput
style={styles.input}
placeholder="Kg"
keyboardType="number-pad"
onChangeText={(kg) => this.setState({kg})}
defaultValue={JSON.stringify(value.weight)} />
<TextInput
style={styles.input}
placeholder="reps"
keyboardType="number-pad"
onChangeText={(reps) => this.setState({ reps})}
defaultValue={JSON.stringify(value.reps)} />
<Button
color="red"
styles={styles.button}
title="Update"
onPress={() =>
this.updateData(key, value.date)
}
/>
<Button
color="red"
styles={styles.button}
title="delete"
onPress={() => this.deleteData(key)}
/>
</View>
</View>
示例组件
class Item extends React.Component {
state = {
kg: '',
reps: ''
}
componentDidMount = () => {
const { kg, reps } = this.props.item;
this.setState({
kg,
reps,
})
}
updateData = () => {...}
render() {
return(
<View>
<TextInput value={this.state.kg} onChangeText={(kg) => this.setState({kg})} ... />
<TextInput value={this.state.reps} onChangeText={(reps) => this.setState({reps})} ... />
<Button color="red" styles={styles.button} title="Update" onPress={() =>this.updateData(key, value.date)} />
<Button .../>
</View>
)
}
}