代码之家  ›  专栏  ›  技术社区  ›  Torben

React Native-将数据从一个组件传递到另一个组件

  •  0
  • Torben  · 技术社区  · 6 年前

    我从别人那里接手了一个React本地项目,这个项目已经很老了(2年),我遇到了以下情况:

    Home.js组件:(我简化了它)

    export let customersData = null;
    
    export default class Home extends Component {  
    
        render() {
            return (
                <JumboButton
                    onPress={() => {
                      this.props.navigator.push({
                        component: CustomerSearch
                      });
                    }}
                  >
            );
        }
    
        _getAllCustomers(limit, sortAttr, order) {
            apiCall.(apiUrl, {
            ...
            }).then((responseData) => {
                const customersDataAll = responseData.data;
                customersData = customersDataAll.filter((f) => {
                    return f.lastname !== ''
                });
            });
        }
    }
    

    客户搜索.js:

    import {customersData} from './Home';
    
    export default class CustomerSearch extends Component {
        constructor(props) {
            super(props);
            this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
            this.state = {
                dataSource: this.ds.cloneWithRows(customersData),
            };
        }
    }
    

    有两件事对我来说有点奇怪:

    1. customersData 而不是 this.customersData 在api调用的回调中?

    2. 目前我得到这个错误 https://d.pr/i/IUzxdf “无法将未定义或空值转换为对象”,我假设这是由于 客户数据

    谢谢你的帮助!

    1 回复  |  直到 6 年前
        1
  •  1
  •   fredmoon    6 年前
    1. 简而言之,这绝对是一种不寻常的反应模式,不是很多人会推荐的。导入 let

    更明智的做法是 customersData 到父组件的 state 把它传给 CustomersSearch 通过一个道具。

    export default class Home extends Component {
      constructor (props) {
         super(props);
         this.state = { customersData: null };
         this._getAllCustomers = this._getAllCustomers.bind(this)
      }
    
      render() {
        return (
            <JumboButton
              onPress={() => {
                this.props.navigator.push({
                  component: props =>
                    <CustomerSearch customersData={this.state.customersData} {...props} />
                });
              }}
            >
        );
      }
    
      _getAllCustomers(limit, sortAttr, order) {
        apiCall.(apiUrl, {
        ...
        }).then((responseData) => {
            const customersDataAll = responseData.data;
            const customersData = customersDataAll.filter((f) => {
                return f.lastname !== ''
            });
            this.setState({ customersData });
        });
      }
    }
    

    不知道你的 JumboButton onPress 道具确实管用,但你应该明白吗?