反应& Redux - 存储更新但组件不存在

时间:2018-03-16 19:01:40

标签: reactjs redux store

看到已经有很多这样的线索,仍然无法找到任何可以帮助我的案例。我敢打赌,这是一个可变性的案例,但我不知道它可能在哪里。每个动作都被调度,Reducer全部获取并且商店更新 - redux devtools确认它,仍然是LoginPage组件没有得到更新,它只在加载/刷新页面上接收initialState。 mapStateToProps仅在安装时调用一次。几天前有不同的页面有同样的问题,但最后和挫折我完全重写了它并且不知道是什么修复了 - 最终代码对我来说是相同的,只有我能想到的事情已经改变了,也许我正在访问商店里的错误字段。

如果有人关心或希望提供帮助,我会很高兴。

以下代码:

LoginPage.js

import React from 'react'
import { connect } from 'react-redux'
import { RoutedComponent } from 'routes/routedComponent'

class LoginPage extends RoutedComponent {
  constructor(props, context) {
    super(props, context)
  }

  state = {
    loginForm: {
      email: '',
      password: '',
    }
  }

  onFieldChange = (event) => {
    const { name, value } = event.target

    this.setState({
      loginForm: {
        ...this.state.loginForm,
        [name]: value
      }
    })
  }

  render() {
    return (
      <div>
        <input type="email" value={this.state.loginForm.email} onChange={this.onFieldChange} />
        <input type="password" value={this.state.loginForm.password} onChange={this.onFieldChange} />
        {this.props.hasFailed && <h4>Something is wrong</h4>}
        {this.props.isLoading && <h4>Logging in...</h4>}
        {this.props.hasLoggedIn && <h4>You are logged in</h4>}
      </div>
    )
  }
}

function mapStateToProps ({ user }) {
  console.log(user)
  return {
    hasLoggedIn: user.hasLoggedIn,
    hasFailed: user.hasFailed,
    isLoading: user.isLoading,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    login: params => dispatch(loginUser(params))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage)

减速

const initialState = {
  isLoading: false,
  hasFailed: false,
}

export function usersReducer(state = initialState, action) {
  console.log(state)
  switch(action.type) {
    case LOGGING_USER:
      return {
        ...state,
        isLoading: true,
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        hasLoggedIn: true,
        isLoading: false,
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        hasFailed: true,
        isLoading: false
      }
    default: return state
  }
}

loginUser操作

export function loginUser(credentials) {
  return dispatch => {
    dispatch(loggingUser())
    tryToLogUser(dispatch, credentials)
  }
}

tryToLogUser功能

export function tryToLogUser(dispatch, credentials) {
  fetch(`${process.env.API_URL}auth/token/`, {
    body: JSON.stringify(credentials),
    headers: {
      'content-type': 'application/json'
    },
    method: 'POST'
  })
  .then((response) => {
    if (!response.ok) {
      throw Error(response.statusText)
    }
    return response
  })
  .then((response) => response.json())
  .then((tokenData) => {
    localStorage.setItem('accessToken', tokenData.access_token)
    dispatch(loginSuccess())
  })
  .catch((error) => dispatch(loginFailure()))
}

以及我合并缩减器的方式

export const makeRootReducer = (asyncReducers) => {
  return combineReducers({
    layout,
    router,
    notifications,
    resources: resourcesReducer,
    user: usersReducer,
    ...asyncReducers
  })
}

RoutedComponent

export class RoutedComponent extends React.Component{
    getLayoutOptions() { return {} };

    componentDidMount() {
        const options = this.getLayoutOptions();

        if(this.props.setCurrentPageSettings) {
            this.props.setCurrentPageSettings(options);
        }

        // Apply the layout settings from the ones provided in the URL
        if(this.props.location.query) {
            const urlSettings = _.mapObject(this.props.location.query,
                val => autocast(val));
            this.props.setLayoutSettingsSafe(urlSettings);
        }

        // Go to Top
        window.scrollTo(0, 0);
    }
}

// Attach restoreSettings action to the Component
export function connect(mapStateToProps = () => ({}), mapActionCreators ={}) {
    const extendedActionCreators = Object.assign([], mapActionCreators, {
        setCurrentPageSettings,
        setCurrentPageSettingsLiteral,
        setLayoutSettingsSafe
    });
    return redux.connect(mapStateToProps, extendedActionCreators);
};

1 个答案:

答案 0 :(得分:0)

我认为你应该在这个地方使用this.state  通过为组件状态分配道具,在组件中提供this.props