首页 > 解决方案 > 在 react-native 中更新 return() 中的变量

问题描述

我对 React 和 React-native 还很陌生,我很难理解我应该如何更新 return 方法中的变量。

目前这是我的代码

import React, { Component } from "react";
import { View, StyleSheet, Platform, Text, Button } from "react-native";

export default class App extends Component<{}> {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick = test => {
    fetch("http://192.168.1.237:3000/thoughts")
      .then(res => res.json())
      .then(res => {
        return (test = JSON.stringify(res));
        return JSON.stringify(res);
      })
      .catch(error => {
        console.error(error);
      });
  };
  componentDidMount() {}

  render() {
    var test = 12314214;

    return (
      <View style={[styles.container]}>
        <Text style={styles.text}>{test}</Text>
        <Button
          onPress={this.handleClick.bind(this)}
          title="Learn More"
          color="#841584"
        />
      </View>
    );
  }
}

我要做的是在单击按钮时更新“{ test }”。该按钮有效,如果我 console.log 按钮测试变量被更新。我猜这里缺少一些基本的东西。任何帮助表示赞赏。

标签: javascriptreactjsreact-nativereact-native-android

解决方案


您的范围不正确,您应该使用 this.setState 导致重新渲染

而不是让一个 var 包含一个值使用

this.state = {test: '124'}

在构造函数中

然后使用

this.setState({test: value_returned_from_fetch })

.then你的取回中

在组件打印内部的返回级别this.state.test

状态说明

因此,在一个反应​​组件中,您在 this.state 中有一个本地状态对象,它可以在构造函数中设置,例如 this.state = {bar: 'foo'};. 构造函数设置状态后,只能使用 this.setState() 方法进行更改。

使用 setState 更改状态后,组件将使用更新的值重新渲染。

该状态在组件之外不可用,至少不能作为 this.state 使用,因为这会调用当前组件的本地状态。

如果您需要使用父组件状态中的值,您可以将其传递给子组件。到那时,它就变成了孩子的道具,可以通过 this.props

要从子组件更改 state 的值,您应该将一个函数传递给更改父组件状态的子组件。

随着应用程序的增长,传递状态更改函数的过程变得越来越复杂,我建议使用像 Redux 这样的库来通过操作和减速器来管理应用程序状态。有一个陡峭的学习曲线,但一旦你掌握了这种修改后的通量方法,你会想知道没有它你是如何生活的。


推荐阅读