【问题标题】:Fetch data is empty in componentwillMount in react native reduxreact native redux中的componentwillMount中获取数据为空
【发布时间】:2017-12-30 19:58:02
【问题描述】:

您好,我正在尝试从 Stephen Grider 的 react-native 课程中学习 react native。我坚持从我的 web 服务加载数据并使用 redux 和 lodash 列出它们。我可以成功获取数据并可以在渲染中看到它(console.log) ,但我的道具在 componentDidUpdate 或 componentWillMount 中始终为空。 任何帮助表示赞赏,谢谢。 减速机是这样的;

    import { TEST_FETCH, TEST_LOAD } from "../actions/types";

const INITIAL_STATE = { dataSource: [] };

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case TEST_FETCH:
      return { ...state, loading: false, dataSource: action.payload.data };
    case TEST_LOAD:
      return { ...state, loading: true, error: "" };
    default:
      return state;
  }
};

动作是;

    import { TEST_LOAD, TEST_FETCH } from "./types";
export  const  getdata = ( ) => {
  return  dispatch => {
    dispatch({ type: TEST_LOAD });
     fetch("http://myserver/getdata", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then(response => {
        return response.json();
      })
      .then(responseData => {
        return responseData;
      })

      .then(data => {
        // return data;
        dispatch({ type: TEST_FETCH, payload: data });
      });
  };
};

页面是;

       import _ from 'lodash';
    import React, { Component } from "react";
    import { View, Text, ListView } from "react-native";
    import { connect } from "react-redux";
    import { getdata } from "../actions";

    class testList extends Component {
      componentWillMount() {
       this.props.getdata();
      }
      componentDidMount() {
       console.log(this.props.myarray ); // myarray is empty
        this.createDataSource(this.props.myarray);
      }

      componentDidUpdate() {
       console.log(this.props.myarray ); // I tried this but still myarray is empty
        this.createDataSource(this.props.myarray);
      }
      createDataSource({ dtsource }) {
// sure dtsource is null too
         const ds = new ListView.DataSource({
          rowHasChanged: (r1, r2) => r1 !== r2});
         this.dataSource = ds.cloneWithRows(dtsource);
      }
      render() {
    console.log(this.props.myarray); // if I write here,I can see my json's output
        return <View>
            <Text>Employee List</Text>
            <ListView dataSource={this.props.myarray} renderRow={rowData => <Text
                >
                  {rowData}
                </Text>} />
          </View>;
      }
    }

    const mapStateToProps = state => {
      const myarray= _.map(state.testForm.dataSource, function(v) {
        return { ...v };
      });
          return { myarray};
    };
    export default connect(mapStateToProps , { getdata })(testList);

【问题讨论】:

  • 您应该从 componentDidMount 发送您的操作。见reactjs.org/docs/react-component.html#componentwillmount
  • this.props.arr1 来自哪里?
  • @CarlosC 对不起,我在这里写的时候忘记改了。这是 myarray
  • 您将mapDispatchToProps 传递给connect()。应该是mapStateToProps
  • @AdamKipnis 我更正了,但我在这里写错了。对不起

标签: react-native react-redux


【解决方案1】:

我建议您使用 FlatList,因为 ListView 已被弃用并且性能不佳。同时,您可以使用下面的代码 sn-p 将正确的对象传递给 dataSource。根据传递给myarray 的数据状态,您可能需要添加一些null 检查。

import _ from 'lodash';
import React, { Component } from "react";
import { View, Text, ListView } from "react-native";
import { connect } from "react-redux";
import { getdata } from "../actions";

class testList extends Component {

  constructor(props) {      
    super(props);               
    this.state = {      
    dataSource: new ListView.DataSource({       
      rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(props.myarray ? props.myarray : [])      
    };      
  }

  componentDidMount() {
    this.props.getdata();
  }

  componentDidUpdate() {
    this.setState({     
       dataSource: this.state.dataSource.cloneWithRows(props.myarray ? props.myarray : [])      
    });
  }

  render() {
    return <View>
        <Text>Employee List</Text>
        <ListView dataSource={this.props.myarray} renderRow={rowData => <Text
            >
              {rowData}
            </Text>} />
      </View>;
  }
}

const mapStateToProps = state => {
  const myarray =  _.map(state.testForm.dataSource, function(v) {
    return { ...v };
  });
      return { myarray};
};
export default connect(mapStateToProps , { getdata })(testList);

【讨论】:

  • 感谢您的评论,我尝试过但收到错误“TypeError: Cannot convert undefined or null to object”。也许我的问题有所不同,我对反应非常陌生,所以我猜仍然不知道一些基本的东西。顺便说一句,我在 mapStateToProps 中看到了我的 json 数据; console.log(state.testForm.dataSource)
  • 我更新为进行空/未定义检查。我在评论中提到,如有必要,可以根据您的数据状态执行类似操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
相关资源
最近更新 更多