Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

javascript - React Native:错误:“无法读取未定义的属性'名称',”尽管包含名称的对象并非未定义(React Native: Error:“Cannot read property 'name' of undefined, ” Although object which contains name is not undefined)

I am new to react and working on a project in react native.(我是新来做出反应的人,并在React Native中从事项目。)

I have loaded data from the server using fetch, Data is available, if i console it shows up, but when i render the data it show undefined.(我已经使用fetch从服务器加载了数据,如果我显示了控制台,则数据可用,但是当我渲染数据时,它显示为未定义。) Being from angular background i know the data is available late for rendering, if i put some conditions then the error will go away.(从背景角度来看,我知道数据可以后期渲染,如果我提出一些条件,那么错误就会消失。) What i want is not to put condition on every single variable, What is the better way to manage it like we use " *ngIf " in Angular on whole content, show only if data is available.(我想要的不是在每个变量上都加条件,有什么更好的方法来管理它,就像我们在整个内容的Angular中使用“ *ngIf ”一样,仅在数据可用时显示。) what i tried so far is below.(我到目前为止尝试过的是下面。) Fetching Data(取得资料) componentDidMount() { this._fetchData(); } _fetchData = () => { if (this.state.loading) { return; } this.setState({ loading: true }); let typr = this._returnReqType(this.state.requestType) let include = [ 'application', 'association:id,name', 'unit:id,unit_number', 'status_history', 'status_history.user', ]; EservicesService.getEservicesRequestDetails(this.state.requestId, typr, include).then(response => { console.log(response.record); // {prop1:'XXXXXXX',association:{name:'Association 1', ...}, ... } console.log(response.record.association); // {name:'Association 1', ...} this.setState({ error: response.error || null, loading: false, request: response.record }); }).catch(error => { this.setState({ error, loading: false }); }); } Rendering Data(渲染数据) render() { console.log(this.state.request); // {prop1:'XXXXXXX',association:{name:'Association 1', ...}, ... } console.log(this.state.request.association); // {name:'Association 1', ...} return ( <View style={{ flex: 1 }}> <ScrollView> <Card > <Text>Association: {this.state.request.association_id}</Text> <Text>Unit: {this.state.request.association.name}</Text> {// Error Here "Cannot read 'name' of undefined" } </Card> </ScrollView> </View> );}   ask by Imdad Ali translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to check if the name is available, then render it.(您需要检查名称是否可用,然后进行渲染。)

{ this.state.request.association && <Text> Unit: {this.state.request.association.name && this.state.request.association.name} </Text> }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...