首页 > 解决方案 > 错误:您可能无法在 reducer 执行时调用 store.getState()(不是开发工具或记录器问题)

问题描述

我试图禁用 Redux 开发工具和记录器,它不是开发工具或记录器问题。尝试更改中间件的顺序,也不起作用。

行动

export const authUser = (userData) => dispatch => {
const dataQ = function getFormData(object) {
    const formData = new FormData();
    Object.keys(object).forEach(key => formData.append(key, object[key]));
    return formData;
}

const dataAuth = {
    wh_country_code : 'US',
    token : userData.accessToken,
    social : 'facebook'

}

dispatch({
    type: 'LOGIN_SUCCESSFULL',
    payload : userData
})

fetch('http://localhost/api/user/auth', {
    method: 'POST',
    body: dataQ(dataAuth)
  }).then( response => {

      if(response.status == 200) {
        console.log(response.status)

      } else {
    // POST to register user if user dont exist
        fetch('http://localhost/api/user/register/facebook', {
            method: 'POST',
            body : dataQ(dataReg)

        })
       }
   })}

零件

import React from 'react';
import PropTypes from 'prop-types'
import Facebook from 'react-facebook-login';
import Google from 'react-google-login';
import socialStyle from '../../css/Components/Account_public/Social.css';
import history from '../../history'
import store from '../../store'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { authUser } from '../../actions/authActions'

/*const googleStyle = {

background: `#db4437`,
marginTop: `20px`,
border: `1px solid #db4437`,
maxWidth: `165px`,
height: `45px`,
position: `relative`,
fontSize: `20px`,
fontWeight: `normal`,
lineHeight: `1.48`,
letterSpacing:` -0.5px`,
textAlign:` left`,
color: `#ffffff`,
top:`-114px`,
left:`24px`
}*/

class Social extends React.Component{
constructor() {
    super();
    this.state= {
        isLoggedIn: false,
        userID: '',
        name: '',
        email: '',
        picture: '',
        token : '',
        wh_country_code : 'US',
        social : 'facebook',
    }
    this.responseFacebook = this.responseFacebook.bind(this);
    this.responseGoogle = this.responseGoogle.bind(this);
}

responseFacebook  (response)  {
     // Split name that Facebook object returns into "first_name", and "last_name"
    var fullName = response.name;
    var index = fullName.indexOf(" ");
    var first_name = fullName.substr(0, index);
    var last_name = fullName.substr(index + 1);
    // Authentication (Login) data sent to API

    // Registration data sent to API
    const dataReg = {
        token : response.accessToken,
        wh_country_code : 'US',
        first_name: first_name,
        last_name: last_name,
        email : response.email,
    }

    this.props.authUser(response)
    // POST to authenticate user
    /* fetch('http://localhost/api/user/auth', {
    method: 'POST',
    body: dataQ(dataAuth)
  }).then( response => {
      if(response.status == 200) {

      } else {
        // POST to register user if user dont exist
        fetch('http://localhost/api/user/register/facebook', {
            method: 'POST',
            body : dataQ(dataReg)

        })
      }
  }) */

}


responseGoogle (response) {
    // Function to convert data from JSON to FormData
    const dataQ = function getFormData(object) {
        const formData = new FormData();
        Object.keys(object).forEach(key => formData.append(key, 
 object[key]));
        return formData;
    }
            // Register with google parameters
    const googleReg = {
        first_name : response.profileObj.givenName,
        last_name : response.profileObj.familyName,
        email : response.profileObj.email,
        token : response.accessToken,
        wh_country_code : 'US'
    }
    // Auth with google parameters
    const googleAuth =  {
        token : response.accessToken,
        wh_country_code : 'US',
        social: 'google'
    }


    fetch('http://localhost/api/user/auth', {
        method : 'POST',
        BODY : dataQ(googleAuth)
    }).then(response => {
        if(response.status == 200) {
            this.setState({
                isLoggedIn: true
            })


        } else {
            console.log(response)
            this.setState({
                isLoggedIn : false
            })
            fetch('http://localhost/api/user/register/google', {
                method : 'POST',
                body : dataQ(googleReg)
            })
        }
    })
}

logout() {
    fetch('http://localhost/api/user/logout', {
        method : "POST",
    })
    this.setState({
        isLoggedIn: false,
        accessToken : '',
    })
}

render(){
    var divstyle = {
        color: 'red',
        fontWeight: '600'
    }
    let fbContent;
    let googleContent;
    let dragica = '1'
    if(this.state.isLoggedIn) {
        fbContent = null;
    } else {
            fbContent = (
                <Facebook
                    appId="111232816261"
                    autoLoad={false}
                    fields="name,email,picture"
                    onClick={this.componentClicked}
                    callback={this.responseFacebook}
                    textButton="Facebook"
                    cssClass="facebook-btn"
                    />

            );
    }

    if(this.state.isLoggedIn) {
        googleContent = null;
    } else {
            googleContent = (
                <Google
                    clientId="426090696509-g9qgpjjrtf4b4d3tuqarslp3na4ehufp.apps.googleusercontent.com"
                    buttonText="Google"
                    onSuccess={this.responseGoogle}
                    onFailure={this.responseGoogle}
                    className="google-btn"
                />
            );
    }

    return(
        <div className="SocialLoginWrap">
                {fbContent}
                {googleContent}
        </div>
    );
}

}




Social.propTypes = {
authUser : PropTypes.func.isRequired
}

export default withRouter(connect(null, { authUser })(Social));

减速器

import history from '../history'
const initialState = {
isLoggedIn : false,
}
const authReducer = (state= initialState, action) => {
switch(action.type) {
    case 'LOGIN_SUCCESSFULL':
     history.push('/')
     return {
         state : true,
         payload : action.payload
     }

    case 'LOGIN_FAILED':
     alert('Failed login idiot')

    case 'LOGOUT': 
     history.push('/account')   
     return null
    default:
     return null
}
}


export default authReducer

如果有人有任何建议,请说,我在这个问题上停留了好几天。我尝试了很多东西,并弹出相同的错误。完整的错误描述:

sdk.js:108 Uncaught Error: You may not call store.getState() while the 
reducer is executing. The reducer has already received the state as an 
 argument. Pass it down from the top reducer instead of reading it from the 
store.
    at Object.getState (redux.js:114)
    at Object.runComponentSelector [as run] (connectAdvanced.js:37)
    at Connect.componentWillReceiveProps (connectAdvanced.js:168)
    at callComponentWillReceiveProps (react-dom.development.js:12564)
    at updateClassInstance (react-dom.development.js:12774)
    at updateClassComponent (react-dom.development.js:14262)
    at beginWork (react-dom.development.js:15082)
    at performUnitOfWork (react-dom.development.js:17820)
    at workLoop (react-dom.development.js:17860)
    at renderRoot (react-dom.development.js:17946)

标签: reduxreact-reduxrouterredux-store

解决方案


推荐阅读