【问题标题】:React JS Read props data only when I refresh the pageReact JS 仅在我刷新页面时读取道具数据
【发布时间】:2021-01-09 10:09:00
【问题描述】:

我将 React 与功能组件一起使用。当我登录时,我使用history.push('/dashboard') 将用户重定向到仪表板页面。当我在仪表板页面上进行控制台日志时,它会显示props 中的所有可用数据。但是数据不会在页面上呈现,它显示"Uncaught (in promise) TypeError: Cannot read property 'profile' of undefined"。当我刷新页面或在历史记录中使用 { forceRefresh:true } 时,一切正常。

侧边栏组件:

import React,{useEffect} from 'react';
import { Link,withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../../../_actions/users'
import {
    Sidebar,
    UncontrolledButtonDropdown,
    Avatar,
    AvatarAddOn,
    DropdownToggle,
    DropdownMenu,
    DropdownItem
} from './../../../components';

function SidebarTopA(props) {
    const { authentication } = props
    function logout(){
        return (e)=>props.logout()
    }
    return (
        <React.Fragment>
            { /* START: Sidebar Default */}
            <Sidebar.HideSlim>
                <Sidebar.Section className="pt-0">
                    <Link to="/" className="d-block">
                        <Sidebar.HideSlim>
                            <Avatar.Image
                                size="lg"
                                src={authentication.user.user.profile.profile_photo}
                                addOns={[
                                    <AvatarAddOn.Icon
                                        className="fa fa-circle"
                                        color={authentication.loggedIn ? "success" :"warning"}
                                        key="avatar-icon-fg"
                                    />
                                ]}
                            />
                        </Sidebar.HideSlim>
                    </Link>

                    <UncontrolledButtonDropdown>
                        <DropdownToggle color="link" className="pl-0 pb-0 btn-profile sidebar__link">
           {authentication.user.user.first_name} {authentication.user.user.last_name}
                            <i className="fa fa-angle-down ml-2"></i>
                        </DropdownToggle>
                        <DropdownMenu persist>
                            <DropdownItem header>
                            {authentication.user.user.email}
                            </DropdownItem>
                            <DropdownItem divider />
                            <DropdownItem tag={Link} to="/apps/profile-details">
                                <i className="fa fa-fw fa-user mr-2"></i>
                    Your Profile
                    </DropdownItem>
                            <DropdownItem divider />
                            <DropdownItem tag={Link} to="/" onClick={logout()}>
                                <i className="fa fa-fw fa-sign-out mr-2"></i>
                        Sign Out
                    </DropdownItem>
                        </DropdownMenu>
                    </UncontrolledButtonDropdown>
                    <div className="small sidebar__link--muted">
                    {authentication.user.user.profile.job_title}
                    </div>
                </Sidebar.Section>
            </Sidebar.HideSlim>
            { /* END: Sidebar Default */}

            { /* START: Sidebar Slim */}
            <Sidebar.ShowSlim>
                <Sidebar.Section>
                    <Avatar.Image
                        size="sm"
                        src={authentication.user.user.profile.profile_photo} 
                        addOns={[
                            <AvatarAddOn.Icon
                                className="fa fa-circle"
                                color="white"
                                key="avatar-icon-bg"
                            />,
                            <AvatarAddOn.Icon
                                className="fa fa-circle"
                                color="success"
                                key="avatar-icon-fg"
                            />
                        ]}
                    />
                </Sidebar.Section>
            </Sidebar.ShowSlim>
            { /* END: Sidebar Slim */}
        </React.Fragment>

    );

}

function mapState(state) {
    const { authentication } = state
    return { authentication };
}
const actionCreators = {
    logout: userActions.logout
}
const connectedHomePage = withRouter(connect(mapState, actionCreators)(SidebarTopA));
export { connectedHomePage as SidebarTopA };

【问题讨论】:

  • 你能做代码沙箱吗?

标签: reactjs react-redux react-router-dom


【解决方案1】:

最后我用redux-persist包解决了。

我的商店设置是:

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../_reducers';
import { composeWithDevTools  } from 'redux-devtools-extension';
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
    key: 'chedsk',
    storage,
  }
const loggerMiddleware = createLogger();

const persistedReducer = persistReducer(persistConfig, rootReducer)
 
const composeEnhancers = composeWithDevTools({trace: true, traceLimit: 20});
export const store = createStore(
    persistedReducer,composeEnhancers( applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
    ))
   
)
export const persistor = persistStore(store)

在 App 组件中我会这样做。

import { store, persistor } from './_helpers/store';
import { PersistGate } from 'redux-persist/integration/react'
render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.querySelector('#root')
);

【讨论】:

    【解决方案2】:

    在渲染 SidebarTopA 时,配置文件信息似乎不可用。
    我建议你保护它,并摆脱 forceRefresh。
    将此添加到 SidebarTopA 中,在您现有的回报之上(并摆脱 forceRefresh):

    if(!authentication.user || !authentication.user.user || !authentication.user.user.profile){
        return "Loading user profile, please wait..."
    }
    

    【讨论】:

    • 您好,我补充说,在现有返回语句的顶部,错误已经消失,但现在我在页面加载时在侧边栏上什么也不显示,但与之前刷新页面时一样,它工作正常。 if(!authentication.user || !authentication.user.user || !authentication.user.user.profile){ return '' } return (//component) 请再次指导我哪里错了。
    • 很抱歉听到这个消息。正如@adir abargil 所说,您应该创建并共享一个最小的可重现示例代码沙箱。
    • 感谢@Louis 的帮助,我无法制作代码沙箱,因为所有组件都相互耦合,很难将它们拉出来。
    • 现在,我们将 const { authentication } = props, authentication 分配给另一个变量 let auth = authentication 及其工作,但是,我仍然不知道为什么会发生这种情况。我也是这样做的在 nuxt js 及其工作但在 react js.data 中不工作的东西在控制台上可见,但在视图上不显示。
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2021-08-18
    • 2019-08-08
    • 2018-05-02
    相关资源
    最近更新 更多