gpt4 book ai didi

javascript - 从容器外部访问生命周期方法的变量

转载 作者:行者123 更新时间:2023-12-03 03:25:06 24 4
gpt4 key购买 nike

我的容器组件有 componentWillMount() 方法,该方法返回 token 。因此,我需要从组件外部访问此 token 的值。在导出 ContainerComponent 之前的 console.log(token) 给了我未定义.

import React, {Component} from 'react';
import {connect} from 'react-redux';
import Component1 from '../components/Component1.js';
import * as actions from '../actions/index.js';


class ContainerComponent extends Component{

componentWillMount(){
var url = window.location.href;

var urlLength = url.length;
var equalSignPos = url.search('=');
var token = url.substring(equalSignPos+1, urlLength);

document.cookie = `token=${token}`;
console.log('token=',token);
return token;
}

render() {
return (
<div>
<Component1 DataInputParam={this.props.counterValue} BtnClickHandler={this.props.buttonClickedMethod} />
</div>
);
}

}

const mapStateToProps = (state) => {
return{
counterValue: state.RequestButtonCounterReducer,
tokenValue: state.TokenReducer
};
};

const mapDispatchToProps = (dispatch) => {
return {
buttonClickedMethod: () => dispatch(actions.buttonClicked())
};
};

console.log(token);

export default connect(mapStateToProps, mapDispatchToProps)(ContainerComponent);

P.S:我希望将 token 导出到 redux-store。

最佳答案

您需要一个用于接收新 token 的操作以及该操作的操作创建者。如果您有相应的操作和操作创建者,请使用它们。

const RECEIVED_NEW_TOKEN = 'RECEIVED_NEW_TOKEN';

const actions = {
...
setToken: (token) => ({ type: RECEIVED_NEW_TOKEN, token: token }),
...
};

现在,在您的 ContainerComponent 中,您需要分派(dispatch)此操作

const mapDispatchToProps = (dispatch) => {
return {
buttonClickedMethod: () => dispatch(actions.buttonClicked()),
setToken: (token) => dispatch(actions.setToken(token))
};
};

componentWillMount(){
var url = window.location.href;

var urlLength = url.length;
var equalSignPos = url.search('=');
var token = url.substring(equalSignPos+1, urlLength);

document.cookie = `token=${token}`;
this.props.setToken(token);
}

最后,在你的 reducer 中,捕捉 Action

switch (action.type) {
...
case RECEIVED_NEW_TOKEN:
// whatever you need to do to place your token in state
// The new token will be in action.token
...
}

关于javascript - 从容器外部访问生命周期方法的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com