我从其他人那里接手了一个React Native项目,这个项目已经很老了(两年),遇到了以下问题:
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 !== ''
});
});
}
}
因此,在家庭组件中,customersData充满了数据。还调用了CustomerSearch组件,在CustomerSearch中我发现了这一点:
CustomerSearch.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),
};
}
}
两件事对我来说有点奇怪:
在api调用的回调中设置customersData
而不设置this.customersData
是否正确?
当前,我收到此错误https://d.pr/i/IUzxdf“无法将未定义或null转换为对象”,我认为这是由于CustomerSearch.js中的customersData
数据导入所致。是我需要看的地方吗?顺便说一句,有什么反应可以告诉我发生此错误的确切行和文件吗?
感谢您的帮助!
答案 0 :(得分: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
的{{1}}道具的工作原理如何,但您应该明白吗?
然后回答2。-是的,我想这是问题所在!