我如何从Redux获取componentDidMount中的令牌?

时间:2020-11-10 08:19:05

标签: react-native react-redux react-props

我正在尝试从redux的componentDidMount内添加道具。 如果我尝试使用componentDidUpdate登录到我的应用程序,则可以看到加载的数据,但是如果我关闭该应用程序并尝试重新打开它,则看不到数据。< / p>

class Profile extends Component {

constructor(props) {
    super(props);
    this.state = {
      results: []
    };
  }

componentDidUpdate = () => {
    this.getMyWeather();
};

getMyWeather = () => {
    const {
      getUser: { userDetails }
    } = this.props;
    axios
      .get(
        settings.host +
          'my_api_url',
        {
          headers: { Authorization: 'Token ' + userDetails.token },
        }
      )
      .then(({ data }) => {
        this.setState({
          results: data.results
        });
      })
      .catch(error => alert(error));
  };

render() {
    return (
      <View style={styles.container}>
        {this.state.results &&
          this.state.results.map((data, index) => (
            <Text key={index}>{data.title}</Text>
          ))}
      </View>
    );
  }
}

let mapStateToProps;
mapStateToProps = state => ({
  getUser: state.userReducer.getUser
});

let mapDispatchToProps;
mapDispatchToProps = dispatch => ({
  dispatch
});

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

在关闭并重新打开应用程序后,我还如何获取数据?

2 个答案:

答案 0 :(得分:0)

尝试这种方式

async componentDidMount() {
    // GET request using axios with async/await
    const {userDetails} = this.props.getUser; <-- Try this way -->
    const data = await this.getMyWeather(userDetails);
    this.setState({
          results: data
    });
}

getMyWeather = async (userDetails) => {
    await axios
      .get(
        settings.host +
          'my_api_url',
        {
          headers: { Authorization: 'Token ' + userDetails.token },
        }
      )
      .then(({ data }) => {
        return data.results;
      })
      .catch(error => alert(error));
};

答案 1 :(得分:0)

为什么首先要在您的Redux中保存令牌? 我个人很容易将它保存在本地存储中。

您知道redux是反应的状态管理,这意味着当您关闭网站时,redux中的数据存储就会死掉,因此,我认为您应该保存在本地存储中,这样才能真正访问它。 如果您将JWT保存在数据库中,则只需要在app.js中的useEffect中调用redux中的操作即可提取JWT并将其保存