Мне нужно динамически создать массив, который передается в средство выбора реакции, чтобы заполнить список дат начала недели, который будет использоваться для заполнения представления ротации.
https://www.npmjs.com/package/react-native-picker-select
Данные должны быть предоставлены в виде массива, как описано в их документах:
The items for the component to render
- Each item should be in the following format:
{label: 'Orange', value: 'orange', key: 'orange', color: 'orange'}
- The label and the value are required
- The key and color are optional
- The key will be set to the label if not included
- The value can be any data type
- Must have at least one item
Я создал функцию, которая использует реквизит данных, содержащий список текста и значений даты начала недели. следующим образом:
dateList = () => {
return( this.props.user.weekCommencingDates.map( (x,i) => {
let dataList= 'label:' + x.Text + ', value:' + x.Value;
return(
dataList;
)
} ));
}
Приведенное выше не предоставляет массив в правильном формате, и я получаю пустой сборщик. может ли кто-нибудь предложить мне какой-либо совет?
Полный класс указан ниже для справки:
import React from 'react';
import { connect } from "react-redux";
import {StyleSheet, Button, View, Text, StatusBar, ScrollView, Picker, FlatList} from 'react-native';
const GlobalStyles = require('../assets/globalStyle');
import { Chevron } from 'react-native-shapes';
import TitleHeader from './util/TitleHeader';
import FixedHeader from './util/FixedHeader';
import CopyrightSpiel from './util/CopyrightSpiel';
import { withNavigation } from 'react-navigation';
import _ from 'lodash';
import moment from 'moment';
import RNPickerSelect from 'react-native-picker-select';
//TODO
//Show current week as initial week
class Rota extends React.Component {
constructor(props) {
super(props);
this.state = {
wcDateSelected: undefined,
rotaList: [],
favNumber: undefined,
numbers: [
{
label: '1',
value: 1,
},
{
label: '2',
value: 2,
},
],
};
}
componentDidMount() {
let thisWeek = this.props.user.weekCommencingDates[0];
this.getData(thisWeek.Value);
}
getData(value){
const rotaList = this.props.user.rotaRecords;
var filteredRotas = rotaList.filter(rota => rota.WeekCommencingDate === value);
this.setState({wcDateSelected: value});
this.setState({rotaList: filteredRotas});
}
dateList = () => {
let dataList = this.props.user.weekCommencingDates.map(x => ({
label: x.Text,
value: x.Value
}));
return dataList;
}
_renderItem = data => {
const item = data.item;
let weekDay= ['Sun','Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
const rotaDay = new Date(item.StartRotaDate).getDay();
const startTime = item.StartTime.substring(0, item.StartTime.length - 3);
const endTime = item.EndTime.substring(0, item.EndTime.length - 3);
return (
<View style = {RotaStyles.tableRow}>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellOne,]}><Text style = {RotaStyles.tableRowText}>{weekDay[rotaDay]}</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellTwo,]}><Text style = {RotaStyles.tableRowText}>{item.Venue}</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellThree,]}><Text style = {RotaStyles.tableRowText}>{startTime}</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellFour,]}><Text style = {RotaStyles.tableRowText}>{endTime}</Text></View>
</View>
);
}
_listEmptyComponent = () => {
return (
<View>
<Text style = {RotaStyles.noRotTxt} >* No rotas available for selected week</Text>
</View>
)
}
_listHeaderComponent = () => {
return (
<View style = {RotaStyles.tableRow}>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellOne, RotaStyles.tableCellHeader ]} ><Text style = {RotaStyles.tableRowHeaderText}>Day</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellTwo, RotaStyles.tableCellHeader ]} ><Text style = {RotaStyles.tableRowHeaderText}>Venue</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellThree, RotaStyles.tableCellHeader ]} ><Text style = {RotaStyles.tableRowHeaderText}>Start</Text></View>
<View style = {[RotaStyles.tableCell, RotaStyles.tableCellFour, RotaStyles.tableCellHeader ]} ><Text style = {RotaStyles.tableRowHeaderText}>End</Text></View>
</View>
)
}
render() {
return (
<View style = {RotaStyles.rotaContainer} >
<StatusBar barStyle = "light-content" />
<View style = {RotaStyles.rotaHeader}>
<FixedHeader backButton = {true} />
</View>
<View style = {RotaStyles.rotaBody}>
<ScrollView>
<TitleHeader sectionLocaleTxt='Shifts' sectionTxt='My Rota' sectionDesc='Your shifts for the selected month' sectionHyphen = {true} />
<Text style = {RotaStyles.pickerTitle} >Scroll to select W/C Date:</Text>
<View style = {RotaStyles.pickerWrap} >
<Text>{this.dateList()}</Text>
</View>
<View style = {[RotaStyles.pickerWrap, {marginTop:30}]} >
<RNPickerSelect
placeholder = {{
label: 'Select a number or add another...',
value: null,
color: 'red',
}}
items = {this.dateList()}
onValueChange = {value => {
this.setState({
favNumber: value,
});
}}
style = {RotaStyles.dropDown}
/>
</View>
<View style = {RotaStyles.rotaTable}>
<FlatList
scrollEnabled = {true}
data = {this.state.rotaList}
keyExtractor = {(item, index) => index.toString()}
ListEmptyComponent = {this._listEmptyComponent}
ListHeaderComponent = {this._listHeaderComponent}
renderItem = {this._renderItem}
/>
</View>
</ScrollView>
</View>
</View>
);
}
}
const RotaStyles = StyleSheet.create({
rotaContainer: {
flex:1,
alignItems:'center',
textAlign:'center',
backgroundColor:'#fff',
alignSelf:'stretch',
},
rotaHeader:{
height:120,
alignSelf:'stretch',
},
pickerTitle:{
fontSize:17,
color:'#1C2344',
fontWeight:'600',
marginBottom:10,
marginTop:15,
marginLeft:15
},
rotaBody:{
backgroundColor:'#fff',
flex:3,
alignSelf:'stretch',
},
dropDown:{
backgroundColor:'#0e131e',
padding:20,
paddingLeft:15,
paddingRight:15,
fontSize:25,
},
rotaTable:{
margin:8,
marginTop:8,
flex:1,
},
tableRow:{
flexDirection:'row'
},
tableCell:{
backgroundColor:'#f3f4f3',
margin:4,
padding:4,
},
tableRowText:{
alignSelf:'center',
},
tableRowHeaderText:{
alignSelf:'center',
fontWeight:'700',
textTransform:'uppercase',
color:'#1C2344',
marginTop:15
},
tableCellOne:{
flex:1,
textAlign:'left',
alignSelf:'stretch',
},
tableCellTwo:{
flex:3
},
tableCellThree:{
flex:2
},
tableCellFour:{
flex:1
},
tableCellHeader:{
backgroundColor:'rgba(255,255,255,0.8)',
},
homeFooter:{
marginBottom:15
},
pickerWrap:{
backgroundColor:'#F4F4F4',
marginLeft:15,
marginRight:15,
},
picker:{
color:'#fff'
},
noRotTxt:{
fontWeight:'700',
justifyContent: 'center',
marginLeft:15,
color:'#f79431',
backgroundColor:'#F4F4F4',
paddingVertical:8,
paddingHorizontal:10,
flex:1,
textTransform:'uppercase',
marginRight:15
},
});
const mapStateToProps = state => {
return {
user: state.user,
isLoading: state.ui.isLoading,
isAuthenticated: state.auth.authenticated,
error: state.auth.error
};
};
export default withNavigation(connect(mapStateToProps, null)(Rota));
Вот скриншот возвращаемого массива в настоящее время:
The
map()
method creates a new array with the results of calling a provided function on every element in the calling array
Итак, предположим, что ваш weekCommencingDates
тоже массив, вы можете сделать это следующим образом:
const dataList = this.props.user.weekCommencingDates.map(x => ({
label: x.Text,
value: x.Value
}))
который для каждого элемента x
массива возвращает новый объект с ключами label
и value
Для меня совершенно невозможно понять, в чем проблема, не видя какой-либо другой части кода, например, метода рендеринга и исходного массива weekCommencingDates.
привет @Milore достаточно честно - я добавил полный код класса и снимок экрана с текущим возвращаемым значением из измененной функции, которую вы указали выше
Похоже, что сборщик используется правильно, но у вас есть <Text>{this.dateList()}</Text>
, который вызывает ошибку, описанную выше. <Text>
компонент принимает строку как дочерний элемент, а не объект
большое спасибо @Milore - я пробовал выше, но получаю сообщение об ошибке - нарушение инварианта: объекты недействительны в качестве дочернего элемента реакции (foundobject with keys {значение метки}