我正在尝试获取用户名、密码并将它们作为参数发送以获取 API 结果,并将结果传递给 contextprovider,将用户重定向到个人资料页面。这工作正常......但是有没有更好的方法可以实现这使用 createcontext??我收到了无法执行反应状态更新的警告......到目前为止我的代码......
mylogin.js
const { setUser } = useContext(UserContexts);
const handlePress = () => {//my button click
const json = {
username: userinfo,
Password: encrypt(password),
};
memberLogin (json).then((userData) => {
if (!Object.keys(userData).includes("error")) {
setUser(userData);
props.navigation.navigate("MyProfile");
} else {
console.log(userData);
}
});
};
myuseraction.js
export const memberLogin = async (json) => {
const json_str = JSON.stringify(json);
try {
const resp = await fetch(
initUrl
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: json_str,
}
);
const responseJson = await resp.json();
return responseJson ;
} catch (error) {
console.log(error);
}
};
contextprovider.js
export const UserContexts = createContext();
export default ({ children }) => {
const [user, setUser] = useState("");
return (
<UserContexts.Provider
value={{
user,
setUser,
}}
>
{children}
</UserContexts.Provider>
);
};
谢谢