我有一个应用程序,系统会提示用户输入代码,它调用外部服务并从 API 返回数据。目前我可以输入代码并调用 api 并获取响应,我还可以每 10 秒轮询一次并返回数据(api 服务上没有套接字)。
我有两个组件,showLanding 和 showResult。 当应用程序初始化时,我想显示 showLanding,提示输入代码并返回 showResult。
我遇到的问题是我无法让它“更新” View 。
我在 getScreen 函数中尝试过 ReactDOM.render 或 render(),我觉得在阅读 React Native doco 时我好像错过了一些明显的东西。
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {showLanding: true, showResult: false}
}
render() {
if (this.state.showLanding) {
return (
<View
tapCode={this.state.tapCode}
style={styles.appContainer}>
{this.state.showLanding && <LandingComponent/>}
</View>
);
}
if (this.state.showResult) {
return (
<View
tapCode={this.state.tapCode}
style={styles.appContainer}>
{this.state.showResult && <ResultComponent/>}
</View>
);
}
}
}
export class LandingComponent extends React.Component {
getResult = (value) => {
this.state = {
tapCode: value.tapcode
}
console.log(this.state);
this.getScreen(this.state.tapCode);
}
getScreen = (tapcode) => {
setInterval(() => (
fetch('https://mywebservice.com/' + this.state.tapCode)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.then(this.state = {
showLanding: false,
showResult: true,
tapCode: tapcode,
resultResponse: this.responseJson
})
.catch((error) => {
console.error(error);
})
), 10000);
}
render() {
return (
<View style={styles.landingContainer}>
landing view, prompt for code
</View>
);
}
}
export class ResultComponent extends React.Component {
render() {
return (
<View style={styles.resultContainer}>
Show json output
</View>
);
}
}
最佳答案
有很多解决方案,但您绝对应该考虑使用像 react-navigation 这样的导航库或react-native-router-flux处理组件之间的路由转换。
我的“脏”建议是:让应用程序组件呈现您的登陆页面并将状态属性“showResults”放在那里。如果 showResult 为 false,则显示代码输入,如果不是,则显示结果。
export class LandingComponent extends React.Component {
constructor(props){
super(props);
this.state = {
showResults: false,
tapcode: null,
resultResponse
}
getResult = (value) => {
this.setState({tapCode: value.tapcode})
this.getScreen(this.state.tapCode);
}
getScreen = (tapcode) => {
setInterval(() => (
fetch('https://mywebservice.com/' + this.state.tapCode)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.then(function(res) {
this.setState({
showResult: true,
tapCode: tapcode,
resultResponse: res.json()})
return res;
})
.catch((error) => {
console.error(error);
})
), 10000);
}
render() {
return (
this.state.showResults ? <ResultComponent/> :
<View style={styles.landingContainer}>
call fetch here....
</View>
);
}
}
并且请永远不要直接改变你的状态!调用setState()相反。
关于javascript - 获取 React Native 后渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632735/