Redux在初始状态之前呈现默认状态 - 服务器端呈现

时间:2016-07-02 12:39:33

标签: javascript reactjs react-redux

我不知道我哪里出错了。但是我在redux中尝试服务器端渲染。当我加载页面时,我很快就会看到提供给reducer的默认值,然后再将其更改为服务器提供的初始状态

这是我的server.js文件

app.use(serveStatic(path.resolve(__dirname, 'public')));
  app.use(cookieParser())
  app.use(passport.initialize())

app.get('/auth/github',passport.authenticate('github'))

  app.get('/auth/github/callback',passport.authenticate('github',{failureRedirect:'/fail'}),
    function(req,res){
      // var text = JSON.stringify({id_token: req.user.token})
      console.log('req.user.token',req.user.token)
      var text=  JSON.stringify(req.user.token)
      //expire in 10 years
      res.cookie('id_token',text,{ expires: new Date(Date.now() + (24 * 60 * 60 * 1000 * 30 * 12 * 10)), httpOnly: true })
      res.redirect('/')
    }
  )

  app.use(handleRender)

  function handleRender(req,res){
    // const store = createStore(rootReducer)
    console.log('handleRender hit')
    console.log('req object',req)
    const html = renderToString(
      Route
    )
    initialState = {UserDetails : {username:'Mikael Akerfeldt'}}
    res.send(renderFullPage(html,initialState))
  }

  function renderFullPage(html,initialState){
    return `
      <!doctype html>
      <html>
        <head>
          <title>Redux Universal</title>
        </head>
        <body>
          <div id="app"><div>${html}</div></div>
          <script>
            window.__INITIAL_STATE__= ${JSON.stringify(initialState)}
          </script>
          <script src="/bundle.js"></script>
        </body>
      </html>`
  }

客户端的index.js文件

const initialState = window.__INITIAL_STATE__

export const store = createStore(rootReducer,initialState)

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={App} />
      <Route path="/hello" component={hello} />
    </Router>
  </Provider>
  ,document.getElementById('app')
)

我的app.js文件

class App extends React.Component{

  componentDidMount(){
    console.log('mounted')
  }

  render(){
    return (
      <div>
        <p> Hello </p>
          <a href="/auth/github">Sign up with github </a>
        <h1> {this.props.username} </h1>
      </div>
    )
  }
}

function mapStateToProps(state){
  const {username} = state.UserDetails
  return{
    username
  }
}

App = connect(mapStateToProps)(App);

export default App

我的减速机

const UserDetails = (state={username: 'anon'},action) => {
  switch(action.type){
    case 'USER_TYPE':
      console.log('reducer hit')
      return Object.assign({},
        state,{username:action.username
        })
        default:
          return state
  }

}

const rootReducer = combineReducers({
  UserDetails
})

正如您所看到的,我已经设置了&#39;用户名&#39;的默认状态。 :我的减速机里的那个。然而,减速器的初始状态是从服务器发送的,用户名是“mikael&#39;

当我加载页面时,this.props.username在更改为“mikael”之前是短暂的。但我的商店正在使用从服务器发送的initialState进行初始化。为什么我仍然看到默认状态?

0 个答案:

没有答案