[英]React redux mapped state to props array is null on update
我正在尝试通过表单更新用户的个人资料,并确保组件在更新时重新呈现,并且在保存后正确的信息显示在表单上。 这是我到目前为止所拥有的:
配置文件输入.tsx
const ProfileInput = ({ user }: any) => {
const updateHandler = () => {
let action;
action = UserAction.updateUser(
formState.inputValues.name
)
setError(null);
setIsLoading(true);
try {
dispatch(action);
setSaveIsDisabled(true);
} catch (err) {
setError(err.message);
setIsLoading(false);
}
setIsLoading(false);
}
if(!user[0]) {
return (<p>loading....</p>);
}
return (
<ProfileInputContainer>
<ProfileInputInnerContainer>
<Form>
<Row>
<Col>
<Form.Group controlId="formGroupName">
<Form.Label>Name</Form.Label>
<Input
authid="name"
type="text"
required
minLength={5}
autoCapitalize="none"
errortext="Name must be at least 5 characters long."
inputchange={inputChangeHandler}
errorhandler={errorHandler}
placeholder="Enter your full name"
initialvalue={user[0].name} />
</Form.Group>
</Col>
</Row>
</Form>
<Row>
<Col>
<CustomButtonContainer>
<CustomButton
fillColour={saveIsDisabled ? Colours.light_grey : Colours.green}
disabled={saveIsDisabled}
onClick={updateHandler}
>
{isLoading ? '...loading' : 'Save'}
</CustomButton>
</CustomButtonContainer>
</Col>
</Row>
</ProfileInputContainer>
</ProfileInputInnerContainer>
)
}
const mapStateToProps = (state: any) => ({
user: state.user.userData
});
export default connect(
mapStateToProps
)(ProfileInput)
加载页面后,用户名将从 state 中获取。 我遇到的问题是当单击保存并分派到 SET_USER 操作时,看起来if(!user[0])
很满意,因为我所看到的只是“正在加载...”。 我不确定为什么当我 console.log out 用户并看到正确的数据时。
用户减速器:
export const userReducer = (state: any = initialState, action: any) => {
switch (action.type) {
case SET_USER:
return { userData: action.userData }
default:
return state;
}
return state;
组件在重新加载并显示加载消息时必须重新渲染,但我不完全确定它为什么会遇到加载消息。 有人可以指出我在这里出错的地方吗?
我认为您应该将道具更改为 state 然后执行 if-else 返回。
React 只有在 React state 发生变化时才会渲染。
目前,您的更改仅在user
的 props 处。
您将不得不使用useEffect
来检测用户道具的变化并更新用户 state 这将导致重新渲染组件。
像这样。
const [userState,setUserState] = useState([]);
useEffect(() => {
setUserState(user);
},[user]);
我给出这个例子是因为你使用的是connect
,它是 Redux 到 map redux Z9ED39E2856props92EFA736 的高阶组件。
但是,您始终可以选择useSelecter
挂钩。
const user = useSelector((state) => state.user.userData);
然后您不需要useEffect
,因为useSelector
已经在您的功能组件内返回 state 作为重新渲染 pivot。 您也可以将connect
和mapStateToProps
排除在图片之外,只需export const ProfileInput
顺便一提,
您应该将 state 散布在减速器中。
case SET_USER:
return { ...state, userData: action.userData }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.