簡體   English   中英

在 API 調用之前反應渲染

[英]React renders before API call

所以我對服務器進行 API 調用以獲取 currentUser,

useEffect(() => {
    loadUser()
},[])

由於 React 的行為就像render first run lifecycle methods second ,首先,我的用戶選擇器返回我期望的 null 。

但是我仍然收到user is null錯誤,所以這是我的代碼 =>

const isAuthenticated = useSelector(state => state.auth.isAuthenticated)
const user = useSelector(state => state.auth.user)

const authLinks = (
    <nav className="auth-navbar">
        <div className="auth-navbar__dropdown">
            <button type="button" className="dropdown-btn" onClick={dropdown}><img src={profilephoto}></img></button>
            <div className="dropdown-menu">
                <Link to={`u/${user.username}`} className="dropdown-link">Profile</Link>
                <Link to="/settings" className="dropdown-link">Settings</Link>
                <Link to="/" onClick={onClickHandler} className="dropdown-link">Logout</Link>
            </div>
        </div>
    </nav>
)
if (user) {
    return (
        <header className="header">
            <Link to="/" className="logo" >
                <img src={logo} alt="logo"/>
            </Link>
            {isAuthenticated ? authLinks : guestLinks}
        </header>
    )
} else {
    return <p>loading..</p>
}

之前在stackoverflow上已經問過這樣的問題,但解決方案與我的類似,但仍然不起作用。 請幫我。

PS: user在reducer中默認為null

編輯:加載用戶的動作創建者 =>

export const loadUser = () => (dispatch) => {

    dispatch({ type: USER_LOADING })

    const config = {
        withCredentials: true
    }

    axios.get('http://127.0.0.1:8000/auth/user/', config)
        .then(res => {
            dispatch({
                type: USER_LOADED,
                payload: res.data
            })
        }).catch(err => {
            console.log(err)
            dispatch({
                type: AUTH_ERROR
            })
        })
}

通常用戶加載沒有錯誤=>

用戶

減速機 =>

const initialState = {
    isAuthenticated: false,
    isLoading: false,
    user: null,
}
export default function(state=initialState, action){
    switch(action.type){
        case USER_LOADING:
            return {
                ...state,
                isLoading: true
            }
        case USER_LOADED:
            return {
                ...state,
                isAuthenticated: true,
                isLoading: false,
                user: action.payload
            } 

我認為您需要使authLinks成為一個僅在user存在時執行並返回相關 JSX 的函數。 實際上,變量將在初始化之前嘗試訪問屬性user.username

const authLinks = () => (
  ...
);

然后在返回中調用它。

{isAuthenticated ? authLinks() : guestLinks}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM