简体   繁体   English

反应 Object 的本机 setState/useState

[英]React Native setState/useState of an Object

I am new to React Native and don't quite understand the concept of initial states of an object and updating the state when I have more than one property to set.我是 React Native 的新手,不太了解 object 的初始状态的概念以及当我要设置多个属性时更新 state 的概念。

the error (edit #2):错误(编辑#2):

Objects are not valid as a React child (found: object with keys {userRole}). If you meant to render a collection of children, use an array instead.

App.js应用程序.js

const initialLoginState = {
    userRole: null,
    userId: null,
};

const [user, setUser] = useState(initialLoginState);
const [isReady, setIsReady] = useState(false);

const restoreUser = async () => {
    const user = await authStorage.getUser();
    if (user) setUser(user);
};

if (!isReady) {
    return (
        <AppLoading
            startAsync={restoreUser}
            onFinish={() => setIsReady(true)}
            onError={console.warn}
        />
    );
}

//render
return (
    <AuthContext.Provider value={{ user, setUser }}>
        <NavigationContainer>
            {user.userRole ? <ViewTest /> : <AuthNavigator />}
        </NavigationContainer>
    </AuthContext.Provider>
);

useAuth which updates the user when I received the data: useAuth 在我收到数据时更新用户:

const logIn = (data, authToken) => {
        setUser((prevState) => ({
            userRole: {
                ...prevState.userId, 
                userRole: data.USERROLE,
            },
        }));
        authStorage.storeToken(data.USERID);
    };

You don't need prevState in functional component.您不需要 prevState 在功能组件中。 user is the prevState before you set new state用户是设置新 state 之前的 prevState

 const logIn = (data, authToken) => { setUser({...user, userRole: data.USERROLE}); authStorage.storeToken(data.USERID); };

Objects are not valid as a React child (found: object with keys {userRole}).对象作为 React 子级无效(找到:object 和键 {userRole})。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

    <AuthContext.Provider value={{ user, setUser }}>  // <---- the problem is here
        <NavigationContainer>
            {user.userRole ? <ViewTest /> : <AuthNavigator />}
        </NavigationContainer>
    </AuthContext.Provider>

I'm not sure what AuthContext.Provider is, but it's trying to render the object(User) as html react elements, make sure you know what sort of data the value prop of that component takes.我不确定AuthContext.Provider是什么,但它试图将对象(用户)呈现为 html 反应元素,确保您知道该组件的value属性需要什么样的数据。

I was able to get the right answer with the help of @P.hunter, @Erdenezaya and @Federkun.在@P.hunter、@Erdenezaya 和@Federkun 的帮助下,我得到了正确的答案。

The problem was in the state init and setUser().问题出在 state init 和 setUser() 中。

  1. App.js应用程序.js
    const initialLoginState = {
        userRole: null,
        userId: null,
    };

    const [user, setUser] = useState({
        initialLoginState,
    });
    const [isReady, setIsReady] = useState(false);

    const restoreUser = async () => {
        const user = await authStorage.getUser();
        if (user) setUser(user);
    };

    if (!isReady) {
        return (
            <AppLoading
                startAsync={restoreUser}
                onFinish={() => setIsReady(true)}
                onError={console.warn}
            />
        );
    }

    //syntax error was found in {user.userRole}
    return (
        <AuthContext.Provider value={{ user, setUser }}>
            <NavigationContainer>
                {user.userRole ? <ViewTest /> : <AuthNavigator />}
            </NavigationContainer>
        </AuthContext.Provider>
    );
  1. Context functionality for setting the user had to be done like this:设置用户的上下文功能必须像这样完成:
export default useAuth = () => {
    const { user, setUser } = useContext(AuthContext);

    const logIn = (data, authToken) => {

        setUser({ ...user, userRole: data.USERROLE });

        authStorage.storeToken(data.USERID);
    };

    const logOut = () => {
        setUser({ ...user, userRole: null });
        authStorage.removeToken();
    };

    return { user, logIn, logOut };
};

Thank you all for your help!谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM