React + Redux,组件在状态发生变化时不会更新

时间:2016-06-02 16:22:47

标签: javascript node.js reactjs redux react-redux

大家好我是redux的新手。我正在创建一个示例应用程序,如下所示:

入口点:index.js

import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import inboundApp from './reducers'
import App from './components/App'

let store = createStore(inboundApp)

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('app')
)

/components/App.js

import React from 'react'
import HeaderContainer from '../containers/HeaderContainer'
import LoginForm from '../containers/LoginForm'

const App = () => (
  <div>
    <HeaderContainer />  
    <LoginForm />
  </div>
)

export default App
< p> /containers/LoginForm.js

import React from 'react'
import { connect } from 'react-redux'
import { login } from '../actions'

let LoginForm = ({ dispatch }) => {
  let input

  return (
    <div>
      <form onSubmit={e => {
        e.preventDefault()
        if (!input.value.trim()) {
          return
        }
        dispatch(login(input.value))
        input.value = ''
      }}>
        <input ref={node => {
          input = node
        }} />
        <button type="submit">
          Login
        </button>
      </form>
    </div>
  )
}
LoginForm = connect()(LoginForm)

export default LoginForm

/actions/index.js

export const login = (supplierId) => {
  return {
    type: 'LOGIN',
    supplierId
  }
}

/containers/HeaderContainer.js

{{ 2}}

/components/Header.js

import { connect } from 'react-redux'
import Header from '../components/Header'

const mapStateToProps = (state) => {
  return {
    supplierId: state.supplierId 
  }
}

const HeaderContainer = connect(
  mapStateToProps,
  null
)(Header)

export default HeaderContainer

/reducers/loginForm.js

import React, { PropTypes } from 'react'

const Header = ({ supplierId}) => {

  return (
      <div>

      <span>Your Supplier ID: </span> {supplierId}
      </div>
  )
}

export default Header

/reducers/index.js

const loginForm = (state = '', action) => {
  switch (action.type) {
    case 'LOGIN':
      return Object.assign({}, state, {
        supplierId: action.supplierId
      })
    default:
      return state;
  }
}

export default loginForm

问题是我的演示文稿组件标题没有通过 LOGIN 获取更新,该操作通过单击<中的按钮来触发strong> LoginForm.js 。

请你帮我找一下我错过的东西?这段代码出了什么问题?

谢谢

1 个答案:

答案 0 :(得分:1)

我认为你试图从错误的命名空间获取supplierId,而你的默认状态loginForm并不好。试试这样:

const loginForm = (state = {supplierId: ''}, action) => {
  switch (action.type) {
    case 'LOGIN':
      return Object.assign({}, state, {
        supplierId: action.supplierId
      })
    default:
      return state;
  }
}

连接

const mapStateToProps = (state) => {
  return {
    supplierId: state.loginForm.supplierId
  }
}