反应:在基于类的组件中获取初始状态

时间:2020-10-30 02:57:20

标签: reactjs react-native redux

我有一个本机的redux应用程序,升级后,我开始收到一些有关生命周期挂钩的警告。我的代码如下:

import React from 'react';
import { connect } from 'react-redux';

import { createStructuredSelector } from 'reselect';
import { selectPosts} from '../redux/selectors/postSelector';
import { getPosts } from '../redux/actions/postActions';

class BasicScreen extends React.Component {
  state = {
    data: [],
    myItems: [],
  };
  componentWillMount() {
    this.getPosts();
  }
  componentDidMount() {
    this.checkforItems();
  }
  getPosts = async () => {
    // Call to a redux action
    await this.props.getPosts();
  };
  
  checkforItems = async () => {
    // myItems in initial state are set from data in 
    AsyncStorage.getItem('MyItems').then(item => {
      if (item) {
        this.setState({
          myItems: JSON.parse(item),
        });
      } else {
        console.log('No data.');
      }
    });
  };

  componentWillReceiveProps(nextProps) {
    // Data comes from the redux action.
    if (
      nextProps.data &&
      !this.state.data.length &&
      nextProps.data.length !== 0
    ) {
      this.setState({
        data: nextProps.data,
      });
    }
  }
  render() {
    return (
      <View>/* A detailed view */</View>
    )
  }
}

const mapStateToProps = createStructuredSelector({
  data: selectPosts,
});

const mapDispatchToProps = dispatch => ({
  dispatch,
  getPosts: () => dispatch(getPosts()),

});

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

总而言之,我从componentWillMount()调用了一个redux动作(this.getPosts()),然后通过componentWillReceiveProps中收到的道具来更新状态。现在这两个都已弃用,并且我收到警告,提示它们已弃用。

除此之外,我还通过从存储中提取一些数据来设置一些初始状态(this.checkforItems())。这给了我另一个警告-无法从其他组件的函数体内更新组件。

在我看来,解决方案就在于将其转换为功能组件,但是,我一直陷于如何调用初始redux动作来设置初始状态的问题。

更新:

我将其转换为功能组件,代码如下:

import React, { Fragment, useState, useEffect } from 'react';
import { connect } from 'react-redux';
import AsyncStorage from '@react-native-community/async-storage';

import { StyleSheet,
  ScrollView,
  View,
} from 'react-native';

import {
  Text,
  Right,
} from 'native-base';
import { createStructuredSelector } from 'reselect';
import {
  makeSelectPosts,
} from '../redux/selectors/postSelector';
import { getPosts } from '../redux/actions/postActions';

const BasicScreen = ({ data, getPosts }) => {

  const [myData, setData] = useState([]);
  const [myItems, setItems] = useState([]);

  const checkForItems = () => {
    var storageItems = AsyncStorage.getItem("MyItems").then((item) => {
      if (item) {
        return JSON.parse(item);
      }
    });
    setItems(storageItems);
  };

  useEffect(() => {
    async function getItems() {
      await getPosts(); // Redux action to get posts
      await checkForItems(); // calling function to get data from storage

      setData(data);
    }
    getItems();
  }, [data]);

    return (
      <View>
        <>
          <Text>{JSON.stringify(myItems)}</Text>
          <Text>{JSON.stringify(myData)}</Text>
        </>
      </View>
    );
}

const mapStateToProps = createStructuredSelector({
  data: makeSelectPosts,
});

const mapDispatchToProps = dispatch => ({
  dispatch,
  getPosts: () => dispatch(getPosts()),
});

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

它可以工作,但是问题在于第一个Text-{JSON.stringify(myItems)}-正在不断重新呈现。该数据实际上是使用checkForItems()获得的。我希望仅在数据更新时才再次调用useEffect,但是正在发生其他事情。

此外,我注意到setData的调用不正确。数据可以通过prop(数据)获得,但不能从状态(myData)获得。 myData只是返回空数组。

0 个答案:

没有答案