null is not an object (evaluating 'this.state.noteArray') - React Native - javascript

Why im receiving this error, but I already add the Constructor at my class.
the error just appear when I execute the android-run start and im getting this error.
null is not an object (evaluating 'this.state.noteArray')
export default class testPoject extends Component {
constructor(props) {
super(props);
this.state = {noteArray: []}
}
render() {
let notes = this.state.noteArray.map((val, key) => {
return <Note key={key} keyval={key} val={val} deleteMethod={ () => this.deleteNote(key)} />
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>TODO LIST </Text>
</View>
<ScrollView style={styles.scrollConainer}>
</ScrollView>
<View style={styles.footer}>
<TouchableOpacity style={styles.addButton}>
<Text style={styles.addButtonText}>
+
</Text>
</TouchableOpacity>
<TextInput style={styles.noteInputText}
placeholder="> Note"
placeholderTextColor="#FFF"
underlineColorAndroid="transparent"
numberOfLines = {3}
/>
</View>
</View>
);
}
}

Well,
Do one thing and it will work. Add a constructor and in that constructor declare the state.
constructor() {
super();
this.state = {
noteArray:[{ 'note': 'Bingo'}],
noteText:'',
}
}

Why are you passing a val and key to your map function? noteArray is an array, not an object with key, value pairs. Ether write noteArray as noteArray: {} or change your map function to work with a single element.

Related

Why cant i pass props to another page? Cannot read proprty of undefined comes up

I'd like to pass the value of localUserId to another screen ( defined in Table.js)
In my App.js i have:
goToTable() {
this.props.navigation.navigate('Table', { userIdForPrivacyToggle: this.state.localUserId } )
}
render() {
return (
<View style={styles.TableButton}>
<TouchableOpacity onPress={()=>this.goToTable()}>
<Icon style={styles.icon} name="list" size={25} color="#FF7400" resizeMode='contain' />
</TouchableOpacity>
</View>
)}
In my Table.js
export default class TableClass extends Component {
constructor(props) {
super(props)
this.state = {
userIdForPrivacyToggle: this.props.navigation.state.params.userIdForPrivacyToggle,
};
Foo() {
Alert.alert(this.state.userIdForPrivacyToggle)
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.Foo}>
<Icon style={styles.icon} name="icon" size={30} color="#FF7400" resizeMode='contain' />
</TouchableOpacity>
</View>
)}
}
When i click the button to call Foo() i get the error:
cannot read property 'userIdForPrivacyToggle' of undefined
Is there something wrong with the onPress methods? What could be going wrong
The Foo() needed to be onPress={()=>this.Foo()}
I am not familiar with <TouchableOpacity /> but usually invoking methods straight away is a bad idea. I guess what you want to do is to pass the method down in order to invoke it where you need it to.
Try this in App.js:
<TouchableOpacity onPress={this.goToTable}>

Passing data to routes navigation React Native

I made a screen of a flatlist that displays a bunch of Doctors infos(name,location,Picture),when i click on a doctor view it navigates to his profil. for the moment the profil screen is just blank, but i want to pass the params so i can just display them without re doing the api call.
here is the code of the research screen where the flatlist is:
render(){
return (
<View style={styles.main_container}>
<FlatList
data={this.state.dataSource}
keyExtractor={item=> item.id.toString()}
renderItem= {({item})=> <MedItem Med={item} />} />
</View>
);
}
i created a component custom med item to style my flat list:
//Meditem.js
class MedItem extends React.Component {
render(){
const Med = this.props.Med
return (
<View style={styles.main_container} >
<View style={styles.ctr1}>
<TouchableOpacity onPress={()=>NavigationService.navigate('MedProfil')}>
<Image style={styles.img} source={require('../assets/Title.jpg')} />
</TouchableOpacity>
<TouchableOpacity onPress={()=>NavigationService.navigate('MedProfil')}>
<Text style={styles.txt}> {Med.name} </Text>
<Text style={{flexWrap:'wrap'}} > {Med.specialite} </Text>
<Text> {Med.work} </Text>
</TouchableOpacity>
</View>
<View style={styles.ctr2}>
<Text style={{textAlign:'center',marginBottom:5}}>Disponibilité</Text>
<Calendar/>
</View>
</View>
);
}
}
last this is my doctor profil screen:
export default class MedProfilScreen extends React.Component {
render(){
return(
<View>
<Text>{Med.name}</Text>
<Button title='Prendre rendez-vous' onPress={()=>{}} />
</View>
);
}
}
Can someone please help me doing this.
thank you
Send Data through navigation like this
this.props.navigation.navigate("MedProfil",
{
name:Med.name
})
Get data in MedProfil Screen
const name=this.props.navigation.getParam("name")
In your Sending component use this:
constructor(props) {
super(props);
this.navigate = this.props.navigation.navigate;
}
//Send it like this
this.navigate("MedProfilScreen", { name:Med.name });
In your receiving component
constructor(props) {
super(props);
this.params = this.props.navigation.state.params;
}
//Can access it using
console.log(this.params.name);
thank you everyone! getParam won't work for me.
i used this to solve the problem
//MedItem.js
<TouchableOpacity onPress={()=>NavigationService.navigate('MedProfil',Med)}>
and in the profil screen
//MedProfil.js
export default function MedProfilScreen({route}){
const {name,specialite,work}=route.params;
return(
<ScrollView contentContainerStyle={{flex:1,alignItems:'center'}}>
<View style={styles.ctr1}>
<Text>{name}</Text>
<Text>{specialite}</Text>
<Text>{work}</Text>

Cannot display array in React Native

When i press the <TouchableOpacity> Button, i want the value 'abc' to be appended to the array selectedTags and then <Text> {this.list()} </Text> will print out my array.
But now when i press the Button, nothing display out.
Can anybody know what is the problem with my code?
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
selectedTags: []
}
}
list() {
return this.state.selectedTags.map(function(tags, i){
return(
<View key={i}>
<Text>{tags.name}</Text>
</View>
);
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => this.state.selectedTags.push('abc')} key = {1} style={styles.buttonContainer}>
<Text style={styles.buttonText}> Button </Text>
</TouchableOpacity>
<Text> {this.list()} </Text>
</View>
);
}
}
This is because you never call setState, which would trigger re-render of your component.
instead of using:
onPress={() => this.state.selectedTags.push('abc')}
try:
onPress={() => this.setState({selectedTags: this.state.selectedTags.concat('abc')})}
The function list only push data in array but does not rerender the view, todo so you have to use setState or forceUpdate.
You can implement the onpress function like this.
onPress = () =>{
this.state.selectedTags.push("abc");
this.setState({selectedTags : this.state.selectedTags});
}

React-Native Navigation without render command

Is there anyway to redirect user to a different component (also passing arguments with it) without calling render function?
almost in all tutorials i found, they use sameway :
render() {
return (
<NavigatorIOS
style={styles.container}
initialRoute=\{\{
title: 'first',
component: First
}} />
);
}
Now see my code :
in renderRow , for touchablehighlights , i need to be able to redirect user to a page with an argument, (in this case i need to send user to component CourseDetail with argument of course_id, so i can show user course's details)
class Courses extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
fetchData() {
// fetching data here
}
componentDidMount() {
this.fetchData();
}
render(){
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<View style={{
flex: 1
}}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
</View>
);
}
renderRow(data) {
var header = (
<View>
<View style={styles.rowContainer}>
<View style={styles.textContainer}>
<Text style={styles.title}>{data.nid}</Text>
<Text style={styles.description} numberOfLines={0}>{data.title}</Text>
</View>
</View>
<View style={styles.separator}></View>
</View>
);
///////////
var cid = [];
var content = [];
for(let x=0; x < Object.keys(data.course).length; x++){
cid[x] = data.course[x].course_id;
content.push(
<TouchableHighlight
underlayColor='#e3e0d7'
key={x}
onPress={()=>{console.log(cid[x]);}} //// i need to navigate user to a page with passing arguments (course_id in this case)
style={styles.child}
>
<Text style={styles.child}>
{data.course[x].title}
</Text>
</TouchableHighlight>
);
}
console.log(cid);
var clist = (
<View style={styles.rowContainer}>
{content}
</View>
);
////////////
return (
<Accordion
header={header}
content={clist}
easing="easeOutCubic"
/>
);
}
renderLoadingView() {
return (
<View style={styles.loading}>
<Text style={styles.loading}>
Loading Courses, please wait...
</Text>
</View>
);
}
}
module.exports = Courses;
Thanks in Advance!
By help of this Question here :
React-Native: Cannot access state values or any methods declared from renderRow
I was able to solve the issue by changing :
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
To :
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
style={styles.listView}
/>
Hope it will help others who may have the same problem.

React Native, setting value of item in state incorrectly

constructor(props) {
super(props);
this.state = {
message: "..",
};
}
render() {
return (
<View style={styles.container}>
<View style={styles.textInput}>
<TextInput onChangeText={(message) => this.setState({message})} placeholder="Enter your message..." style={styles.text}/>
<TouchableHighlight style={styles.button} onPress={this.submit}>
<Text ref="message" onPress={this.submit}>Submit</Text>
</TouchableHighlight>
</View>
</View>
)
}
loadData(){
AlertIOS.alert(this.state.message);
}
componentDidMount(){
this.loadData()
}
submit(){
AlertIOS.alert(this.state.message);
}
When loadData is first called, it shows the current value of message: ".."
When my submit function is called, it throws an error: undefined is not an object (evaluating 'this.state.message')
I'm assuming that it is my onChangeText attribute that's setting message to undefined, but I'm not sure why.
The problem is that this isn't bound correctly in submit()
In your constructor, try adding the line:
this.submit = this.submit.bind(this);

Categories

Resources