我是 React 的新手,在重繪 . 我期待視圖應該顯示
“你好世界!Shyam”
但它只顯示“Hellow World”。
我的代碼:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class WhatsDes extends Component {
constructor(props) {
super(props);
this.state = {name:'', email:''};
}
render() {
console.log('Start render ....');
const url = 'http://192.168.1.13:8091/employees';
fetch(url)
.then(response => response.json())
.then(responseJson => {
console.log('ok 1: ' JSON.stringify(responseJson));
console.log('ok 2: ' responseJson[0].name);
this.state.name = responseJson[0].name;
})
.catch(error => {
console.log('error' error);
});
console.log('Show view ...' );
console.log('this.state.name ...' this.state.name);
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Hello, world ! {this.state.name}</Text>
</View>
);
}
}
日志輸出:
LOG Running "WhatsDes" with {"rootTag":201}
LOG Start render ....
LOG Show view ...
LOG this.state.name ...
LOG ok 1: [{"name":"Shyam","email":"[email protected]"},{"name":"Bob","email":"[email protected]"},{"name":"Jai","email":"[email protected]"}]
LOG ok 2: Shyam
uj5u.com熱心網友回復:
不要改變狀態。如果要更新狀態,請使用該setState方法。
更改您的狀態更新,
this.state.name = responseJson[0].name;
到
this.setState({name: responseJson[0].name});
setState在https://reactjs.org/docs/react-component.html#setstate閱讀更多資訊
編輯:仔細檢查后,發現您的代碼中還有一些 no no。
您正在render函式內部執行所有這些操作。這不是正確的做法。
將您的 API 呼叫移動到componentDidMount函式,它只會在您的組件安裝上執行。在做這件事render,你現在所做的將反復呼叫該函式在每個渲染和將拋出錯誤Max callstack exceeded。
將您的代碼更改為,
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class WhatsDes extends Component {
constructor(props) {
super(props);
this.state = {name:'', email:''};
}
componentDidMount() {
const url = 'http://192.168.1.13:8091/employees';
fetch(url)
.then(response => response.json())
.then(responseJson => {
this.setState({ name: responseJson[0].name });
})
.catch(error => {
console.log('error' error);
});
}
render() {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Hello, world ! {this.state.name}</Text>
</View>
);
}
}
查看生命周期事件也許是個好主意- React
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/312476.html
