2017-06-23 55 views
0

我在index.js以下渲染功能:reactjs設置狀態和index.js使用它

const renderLogin =() => { 
    ReactDOM.render(
     <Provider store={store}> 
      <AppContainer> 
       <Router history={createHistory}> 
        <div> 
         <ThemeProvider theme={theme}> 
          <div className={i.content}> 
           <Route exact path="/" component={() => (<Login foo={"test"}/>)}/> 
          </div> 
         </ThemeProvider> 
        </div> 
       </Router> 
      </AppContainer> 
     </Provider>, 
     rootEl 
    ); 
}; 

在組件登錄我設置一個狀態變量,如果用戶登錄工作

我可以將結果返回給index.js和我們嗎?

回答

2

如果您在Login正在管理的狀態實際上是在你的應用程序的其他地方需要有效地爲全局狀態,有幾個顯而易見的方法可以解決這個問題:

  1. Lifting State Up

簡而言之,不是在該組件中存儲和管理Login的狀態,而是將狀態提升到最近的父節點。然後,通過該狀態下經由道具組件樹,並通過回調備份傳遞值(例如onLoginClick

  • 使用的狀態下的容器中,諸如Redux
  • 相反必須管理父組件中的狀態並通過可能的多層組件通過道具傳遞值/回調,您可以將此狀態集中存儲在單個狀態對象中。然後,您可以讓任何組件訂閱此狀態,並且您可以在有人登錄時通過Redux操作發送修改狀態的意圖。

    派遣一個動作從你的終極版連接組件:

    dispatch(userLogin(userName)); 
    

    操作:

    const userLogin = userName => { 
        return { 
        type: "USER_LOGGED_IN", 
        userName 
        }; 
    }; 
    

    登錄減速機:

    const loginReducer = (
        state = { 
        userLoggedIn: false, 
        userName: null 
        }, action) => { 
        switch(action.type) { 
        case "USER_LOGGED_IN": 
         return { 
         ...state, 
         userLoggedIn: true, 
         userName: action.userName 
         }; 
        default: 
         return state; 
        } 
    } 
    

    我會全力推薦看都丹·阿布拉莫夫的理論家的Redux上的.io視頻系列(帶React):

    這可能是最好的,特別是如果你是新的反應,to try the first approach提升狀態起來。如果你最終發現它變得笨重,那麼讓Redux一槍。

    +0

    index.js不是一個組件我可以使用提升狀態嗎? – Felix

    +0

    我假設你在'index.js'內有一個根組件,最終呈現'Login'。你能否解除這個狀態? – Michael

    +0

    你能詳細說明爲什麼你想要index.js中的值以及你需要怎麼處理它嗎? – Michael

    相關問題