I am unable to update my react hooks state.
So this is what I am doing (this is a minified relevant code).
export const Signup = (props) => {
const key= 'randomKey'
const onTextChangeHandler = (text) => {
console.log(key)
setPayloadData[key] = text
console.log(payload)
}
const [payload, setPayloadData] = useState({})
return (
<View>
<TextInput
placeholder={placeHolder}
number={number}
style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, templateStyle]}
onChangeText={text => onTextChangeHandler(text)}
value={payload[key]}
/>
</View>
)
}
here, In the above code, notice
const onTextChangeHandler = (text) => {
console.log(key)
setPayloadData[key] = text
console.log(payload)
}
Here text is coming out to be whatever I typed. console.log
of the key is returning the randomKey
but
console.log(payload)
Is coming out to be undefined. Can anyone help me in figuring out what I am doing wrong?
setPayload
is a function, not an object. What you are actually doing is assigning a new field to the function, the payload
remains unchanged, since the function responsible for updating it is not being called .
setPayloadData[key] = text; // the function object mutation occures
Solution : simply invoke it as a function and pass the argument you want:
setPayloadData({ [key]: text });
Example: Update state using useState
hook
Update props value and HOC components accordingly
import React, { useState } from 'react';
const Signup = (props) => {
const key= 'userKeyboardStrokes'
const onTextChangeHandler = (event) => {
setPayloadData({ [key]: event.target.value })
}
const [payload, setPayloadData] = useState({})
return (
<React.Fragment>
<input
type="text"
onChange={text => onTextChangeHandler(text)}
/>
</React.Fragment>
)
}
module.exports = Signup;
Output Result:
{
userKeyboardStrokes: "user input on object"
}
Playground Example: https://stackblitz.com/edit/react-npytvn?file=testing.js
setPayloadData
是一个 setter,它应该是setPayloadData(newData)
来更新状态。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.