使用本地存储与react-redux?

时间:2018-06-23 13:46:57

标签: reactjs redux local-storage

我有一个react redux项目,看起来像这样:

Reducer:

union - s

动作:

Y ∪ Z ∪ A ∪ B...

Api本身:

    export function contentReducer(state = { loading: true }, action) {
    switch (action.type) {
        case types.RETRIEVE_CONTENT_SUCCESS:
            return { ...state, loading: false, contentResults: action.payload.results }
        default:
            return state;
    }
};

但是当我尝试像这样从主页访问本地存储时:

export function loginSuccess(loginResult) {
    return { type: types.LOGIN_SUCCESS, loginResult };
}

export function login(formData) {
    return function (dispatch) {
        return submitLogin(formData).then(umvToken => {
            dispatch(loginSuccess(umvToken));
        }).catch(error => {
            throw (error);
        });
    };
}

我收到以下消息:

export function submitLogin(login) {
    var form = new FormData()
    form.append('userIdentifier', login.email)
    form.append('password', login.password)
    return fetch("http://localhost:8080/login/login/umv",
        {
            method: "POST",
            headers: {
                'Accept': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
            body: form

        }).then(function (response) {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            return response;
        })
        .then(function (token) {
            localStorage.setItem('umvToken', token.text())
            return token
        })
        .catch(function (error) {
            console.log('Looks like there was a problem: \n', error);
        })

}


function mapStateToProps(state) {
    return {
        login: state.login.loginResponse
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(thunks, dispatch)
    };
}
class ConnectedHome extends Component {
    constructor() {
        super();
        this.processForm = this.processForm.bind(this);
    }

    processForm(form) {
        this.props.actions.login(form)
    }


    render() {
        return (
            <div>
                {this.ButtonAppBar()}
                <LoginForm onSubmit={this.processForm} />
            </div >
        );
    }
}

const Home = connect(mapStateToProps, mapDispatchToProps)(ConnectedHome);

export default Home

如果我用以下命令替换本地存储设置:

var result = localStorage.getItem('umvToken')
        console.log(result)

然后console.log将显示测试。但这与实际值不符。我不太确定如何解决这个问题?
感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

我很确定token.text()返回一个Promise,因此您需要等待它到达resolve才能获得实际的令牌字符串,即

.then(function (token) {
  return token.text();
})
.then(tokenText => {
  localStorage.setItem('umvToken', tokenText);
})

答案 1 :(得分:0)

从api调用的第一个.then函数return response.json();return response.text();开始。如果仅返回响应,则其承诺将无法解决,除非您根据期望的响应类型进行response.json()或response.text()。

答案 2 :(得分:0)

使用以下代码

.then(function (token) {
            localStorage.setItem('umvToken', JSON.stringify(token))
            return token
        })