我正在使用React Context来存储登录用户的凭据,并创建了一个reducer / action模式来处理逻辑。现在,我能够使用适当的凭据成功登录,但是我还想使用动态参数将用户重定向到他的个人资料,例如:profile/:id
。我的问题是,我不确定如何以与初始调用Context相同的功能访问用户ID,在Context中我用用户的登录凭据填充它。到目前为止,我有:
function Login(props) {
const userContext = useContext(UserContext);
const [credentials, setCredentials] = useState({
username: '',
password: ''
});
async function onSubmit (e) {
e.preventDefault();
const user = await userContext.loginUser(credentials); // Wait for payload...
props.push.history(`/profile${user.id}`); // ...Then use payload (user.id) to redirect to desired endpoint
}
作为参考,这是我的loginUser
动作:
const loginUser = async credentials => {
setLoading();
const response = await axios
.post('endpoint here', credentials)
dispatch({
type: LOGIN_USER,
payload: response.data
})
}
这是我的减速机,其初始状态在其下:
export default (state, action) => {
switch(action.type) {
case SET_LOADING:
return {
...state,
loading: true
}
case LOGIN_USER:
return {
...state,
user: action.payload,
loading: false
}
default:
return state;
}
}
const initialState = {
user: {},
issues: [],
loading: false
}
希望这足以使某人发现我的缺点。任何帮助表示赞赏。