2017-10-21 51 views
0

我收到以下錯誤,雖然我回一個根元素:Route.render():有效的做出反應元素(或空)必須返回

Route.render():有效的做出反應元素(或null)必須返回。您可能返回了未定義的數組或其他一些無效的對象。


調度是不是一個函數


我的代碼:

export var PrivateRoute = ({ component: Component, ...rest }) => { 

    return (
    <Route {...rest} render={props => { 
    firebase.auth().onAuthStateChanged((user) => { 
     if(user) { 
     console.log('ON...ON'); 
     var {dispatch} = props; 
     dispatch(actions.login(user.uid)); 
     dispatch(actions.startAddTodos()); 
     return(
      <Component {...props} /> 
     ) ; 

     } else { 
     console.log('OFF...OFF'); 

     dispatch(actions.logout()); 

     return (
      <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> 
     ); 

     } 
    }); 
    }} />); 
} 
export default Redux.connect()(PrivateRoute); 

Github Link

+0

你的回報是異步回調中,而不是直接返回功能正在'道具'作爲論點 –

+0

@MohammadElbanna:謝謝,你能否提出解決問題的方法,請 –

+0

我發佈了一個解決這個問題的建議。希望它有效! –

回答

2

我認爲主要的問題是你在異步函數中返回UI。

我認爲你的組件應該有一個狀態isLoading向用戶顯示,直到認證操作完成。 當isLoading爲真時,您應該顯示加載指示器 否則,您應該顯示與驗證成功或失敗相關的其他組件。

您還應該定義auth成功或失敗的狀態。

:我打算用反應組件狀態的系統,而不是終極版,因爲我不知道很多關於你的終極版狀態樹。隨意嘗試將其轉換爲Redux

首先,您應該重構要在單獨的類組件中路由到的組件。讓我們稱之爲 組件UserAuth

class UserAuth extends Component { 
    state = { 
    isLoading: true 
    isUserAuth: false 
    } 

    componentDidMount() { 
    firebase.auth().onAuthStateChanged((user) => { 
     if(user) { 
     this.setState({isLoading: false, isUserAuth: true}) 
     // the rest of your logic here 
     } 
     else { 
     this.setState({isLoading: false, isUserAuth: false}) 
     // the rest of your logic here 
     } 
    } 

    render() { 
    return (
     {this.state.isLoading && <LoadingIndicator /> } 
     {!this.state.isLoading && this.state.isUserAuth && <Component {...this.props} />} 
     {!this.state.isLoading && !this.state.isUserAuth && <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />} 
    ); 

    } 
} 

其次,在你<Route>組件,你應該這樣做:

<Route {...rest} render={props => (<UserAuth {...props} />)} /> 
+0

ميرسيخالصيامحمد,أنالسهجديدفيالموضوعففيحاجاتكتيرمشواضحةبالنسبالي,كنتبتمنىيكونالتعديلعلىنفسالمثال,لانال '路由器V4' مختلفتمامافحسبالاقتراحاتاطلبانياعمل '重定向Component' فياللينك دا https://stackoverflow.com/a/46799951/418343 وحضرتكبتقولياعمل 新組件! 即將發佈。 –

+1

العفوياباشا..اناحكملانجلشعشانلوحدممكنيستفيدبحاجة..قولليبسايهالليمشواضحواناافهمك(لوعارفيعني 我沒有做太多,我只是重構你的代碼。需要進行重構你的代碼因爲正如我所說你不能從異步回調中返回UI。您正在創建組件(並將其傳遞給屬性),我所做的只是給它起了個名字並重構了它的代碼。請注意,它是React.js的方式,通過組件始終創建可重用的代碼。順便說一下,PrivateRoute組件(在你發佈的鏈接上)是保證路由安全的一個很好的抽象。 –

+1

謝謝Mohammad,我會試試看:) –

相關問題