リストに表示する一連のオブジェクトがあります。各フィールドには、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>
)
変更を状態に保存する必要があります。お気に入り
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>
)
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加