我到处都在搜索此反应挂钩情况,但似乎无法获得答案。因此,基本上我是从后端获取用户数据的,并将其存储在redux存储中。现在的问题是,我想从redux中获取该对象数据,使用useEffect将其设置为useState的初始值,并在按下Submit之后更新状态值
redux存储中存储的数据示例
{bio: null, created: "2019-11-20T02:48:52.152991", id: 1, image: null,last_seen: null,name: "john", username: "john"}
我的组件
function ModalWindow (props){
const[values, setValues] = useState(props.userData)
useEffect(()=>{
setValues(props.userData)
}, [props.userData])
const onChangeHandler = (e) =>{
const{name, value} = e.target;
setValues({...values, [name]: value})
}
return (
<div className="modal-window">
<Modal.Dialog>
<Modal.Body>
{props.userData.length > 0 &&
<Form>
<Form.Group>
{console.log( values[0])}
<Form.Label>Name</Form.Label>
<Form.Control
name="name"
type="text"
onChange={onChangeHandler}
value={values.name}
placeholder="Enter name" />
</Form.Group>
<Form.Group>
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
value={username}
readOnly
/>
</Form.Group>
<Form.Group>
<Form.Label>Image Url</Form.Label>
<Form.Control
name="image"
type="text"
onChange={onChangeHandler}
value={values.image}
placeholder="Enter image url" />
</Form.Group>
<Form.Group>
<Form.Label>Bio</Form.Label>
<Form.Control
name="bio"
onChange={onChangeHandler}
value={values.bio}
as="textarea" rows="3" />
</Form.Group>
</Form>
}
</Modal.Body>
<Modal.Footer>
<Button onClick={onClose} variant="secondary">Close</Button>
<Button onClick={addItem} variant="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
)
}
const mapStateToProps = state =>({
userData: state.userReducer.userData
})
export default connect(mapStateToProps, null)(ModalWindow);