javascript - React redux 映射状态到 props 数组在更新时为空
问题描述
我正在尝试通过表单更新用户的个人资料,并确保组件在更新时重新呈现,并且在保存后正确的信息显示在表单上。这是我到目前为止所拥有的:
配置文件输入.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)
加载页面后,用户的姓名会从状态中很好地获取。我遇到的问题是当单击保存并分派到 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;
组件在重新加载并显示加载消息时必须重新渲染,但我不完全确定它为什么会遇到加载消息。有人可以指出我在这里出错的地方吗?
解决方案
我认为您应该将道具更改为状态,然后执行 if-else 以返回。
React 只会在 React 状态发生变化时渲染。
目前,您的更改仅在 props 是user
.
您将不得不使用useEffect
来检测用户道具的变化并更新用户状态,这将导致组件的重新渲染。
像这样。
const [userState,setUserState] = useState([]);
useEffect(() => {
setUserState(user);
},[user]);
我给出这个例子是因为你使用connect
的是 Redux 的一个高阶组件来将 redux 状态映射到你的组件 props 中。
但是,您始终可以选择useSelecter
挂钩。
const user = useSelector((state) => state.user.userData);
那么你就不需要了,useEffect
因为它useSelector
已经在你的功能组件中返回了一个状态作为重新渲染枢轴。connect
你也可以离开mapStateToProps
图片export const ProfileInput
顺便一提,
你应该在你的减速器中传播你的状态。
case SET_USER:
return { ...state, userData: action.userData }
推荐阅读
- jquery-ui - jqueryui 1.10.3 datepicker 格式使用 . 作为分隔符
- windows - PGAdmin 4 调试器不工作?在 Windows 10 x64 上
- vim - 有什么方法可以在 Vim 中的行号后添加额外的空格?
- webpack-dev-server - 使用纱线工作区时出现错误的 webpack 开发服务器
- spring-boot - Spring Boot 应用程序无法启动端口可能已在使用错误
- c# - 管道请求有问题。系统只是退出并且不继续
- javascript - React Native 响应儿童新闻事件
- bash - bash - 拆分字符串时失败,但 zsh 正在工作
- r - 条形图子组因子重新排序不起作用
- intellij-idea - Cannot run @QuarkusTest annotated unit tests with IntelliJ IDEA