Just learning rn, there are many places that do not understand, often report undefined is not an object this error, and then constantly modify and try the case of error.
To discover that this exists whenever this happens, first post an incorrect code
export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "I am header",
_data: [
{key: 'a'},
{key: 'b'},
{key: 'c'},
{key: 'd'},
{key: 'd'},
]
}
}
_header() {
return (
<Text style={{backgroundColor: "red", height: 100,}}>
{this.state.header}
</Text>
);
}
render() {
return (
<View>
<FlatList
ListHeaderComponent={this._header}//Header header component
data={this.state._data}
renderItem={({item}) => <Text style={{alignSelf: "center", flex: 1, height: 30}}>{item.key}</Text>}
/>
</View>
);
}
}
False report
It's a mistake to say this.state.header. It's depressing to have just touched on it. Isn't it the same way to quote values from state?
I tried to write a simple demo.
export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "I am header",
}
}
render() {
return (
<View>
<Text>{this.state.header}</Text>
</View>
);
}
}
It's absolutely OK. It gives me a headache as a beginner in rn. Later, I wondered if it would be related to this.
I tried to delete {this.state.header} and add a fixed value at random. It was perfectly possible. Later, I thought, the _header function was a FlatList component.
Is this a sub-component of the _header() function pointing to the FlatList component? How can I get the whole picture of this?
Later, I looked at the following information and found a solution, which is to bind the _header() function to the global this. The default this is to point to the parent component.
export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "I am header",
_data: [
{key: 'a'},
{key: 'b'},
{key: 'c'},
{key: 'd'},
{key: 'd'},
]
}
//Binding global this to the _header function
this._header=this._header.bind(this)
}
_header() {
return (
<Text style={{backgroundColor: "red", height: 100,}}>
{this.state.header}
</Text>
);
}
render() {
return (
<View>
<FlatList
ListHeaderComponent={this._header}//Header header component
data={this.state._data}
renderItem={({item}) => <Text style={{alignSelf: "center", flex: 1, height: 30}}>{item.key}</Text>}
/>
</View>
);
}
}
summary
1. this that the child component points to belongs to the child component and is independent of the parent component.
2. The child component cannot update the status of the parent component
3. If you want to update the state of the parent component in the child component, bind the parent component to the child component's this