【发布时间】:2020-08-01 13:56:52
【问题描述】:
它尝试过这样使用
{ options.map( opt => {
return <Text>{opt.value}</Text>
}) }
这里我从后端获取数据并传入到 DetailScreen。
class Poll extends Component {
state = {
loading:true,
pollDetails : []
}
componentDidMount(){
fetch('http://192.168.43.22:5000/api/v1/questions/5f1c31e1089847468cb9c508')
.then((response) => response.json())
.then((responseJson) => this.setState({pollDetails:responseJson.data}));
this.setState({loading:false});
}
render() {
const {loading, pollDetails} = this.state;
if(loading){
<View>
<Text><ActivityIndicator/></Text>
</View>
}
return(
<ScrollView>
<DetailsScreen
key={pollDetails._id}
title={pollDetails.title}
options={pollDetails.options}
voteCount={pollDetails.voteCount}
opinionCount={pollDetails.opinionCount}
loaded={true}
votes={60}
/>
</ScrollView>);
}
}
在这里我尝试映射选项,但它抛出错误!
import React, {Component} from 'react';
import {View, Text, StyleSheet, Animated, TouchableOpacity} from 'react-native';
import Card from '../UI/Card';
export default class DetailScreen extends Component{
state = {
width:0,
voteCount: this.props.voteCount
}
handleOnLayout = ( {nativeEvent} ) => {
this.setState({width:nativeEvent.layout.width})
}
handleVotes = (id) => {
console.log(this.state.voteCount)
}
render(){
const {title, voteCount, votes, opinionCount, loaded} = this.props;
const _animatedWidth = new Animated.Value(0);
const animatedAnswerValue = () => {
const percentage = votes / voteCount;
const rowWidth = Math.floor(this.state.width * percentage);
Animated.timing(_animatedWidth,{
toValue:rowWidth,
duration:1500
}).start();
}
animatedAnswerValue();
const getOverlayStyles = (votes) => {
const s = [styles.optionBar];
if(votes > 50){
s.push(styles.optionBarHigh);
}
if(votes < 50 && votes > 20){
s.push(styles.optionBarMedium);
}
if(votes <= 20){
s.push(styles.optionBarLow)
}
return s;
}
return(
<View style={{marginLeft:100}}>
<Text style={{marginTop:50}}>{title}</Text>
{
this.props.options.map((opt,index) => {
return <Text key={index}>{opt.votes}</Text>
})
}
<Text>Just some sample text here!!!</Text>
{/* <TouchableOpacity key={options._id[0]} onPress={() => this.handleVotes(options._id)}>
<Card>
<Text>{options.value}</Text>
<View style={styles.optionBarRow} onLayout={this.handleOnLayout}>
<Animated.View
style={[getOverlayStyles(this.props.votes,loaded), {width:_animatedWidth}]}/>
<View style={styles.opinions}>
<Text style={{textAlign:"center"}}>Opinions</Text>
</View>
</View>
</Card>
</TouchableOpacity> */}
</View>
);
}
}
但它会抛出“无法读取未定义的属性'map'的错误
我最近一直在挠头.. 如果有人帮我解决这个问题,我会很高兴的! 在此先感谢:)
【问题讨论】:
-
你是怎么到达
options的?贴出完整代码 -
第一个问题,你如何使
options可用于此组件? -
这个错误意味着它认为
options不存在。因此,无论您在哪里调用该代码,请确保您正确获取选项。你确定不需要data.options吗? -
我已经更新了我的问题,请查看
标签: javascript html css reactjs react-native