【问题标题】:Cant write the state inside a Text无法在文本中写入状态
【发布时间】:2021-04-06 09:53:41
【问题描述】:
export default class App extends React.Component {
  constructor(){
    super();
    this.state = {
      ready: false,
      where: {lat:null, lng:null, adr:null},
      error: null,
      temps: 8,
    }
  } 
  geoSuccess = (position) => {
    this.setState({
      ready:true,
      where: {lat: position.coords.latitude, lng:position.coords.longitude},
    })
    let latit = this.state.where.lat
    let lonit = this.state.where.lng
    var latitAbc = latit.toFixed(4)
    var lonitAbc = lonit.toFixed(4)
    let latitStr = latitAbc.toString()
    let lonitStr = lonitAbc.toString()
    console.log(latit)
    console.log(lonit)
    
    const options = {
      method: 'GET',
      url: 'https://weatherapi-com.p.rapidapi.com/forecast.json',
      params: {q: (latitStr+','+lonitStr)},
      headers: {
        'x-rapidapi-key': 'f7982bbb0dmsh562cc7597c785bbp1857b5jsn07695d566c0b',
        'x-rapidapi-host': 'weatherapi-com.p.rapidapi.com'
      }
    };
    axios.request(options).then(function (response) {
      let temp = response.data.current.temp_c
      console.log(temp);
      this.setState({
        temps: temp
      })
    }).catch(function (error) {
      console.error(error);
    });
  }
  geoFailure = (err) => {
    this.setState({error: err.message})
  }
  render(){
    return (
              <Text style={styles.konum}>{
              `Konumunuz Enlem: ${this.state.where.lat} Boylam: ${this.state.where.lng} Sıcaklık:${this.state.temps}`
              }
              </Text>
    );
  }
}

我正在尝试制作一个天气应用程序,我正在从地理定位器获取纬度和经度,并在天气 api 中使用此变量,但是,

我无法将我从天气 api 获取的临时变量写入文本。 我想我需要对 react-native 中的 state 和 useState 的帮助

【问题讨论】:

    标签: javascript react-native react-hooks state setstate


    【解决方案1】:

    你不需要在 JSX 中使用模板文字,下面的代码就可以了

    <Text style={styles.konum}>
              Konumunuz Enlem: {this.state.where.lat} Boylam: {this.state.where.lng} Sıcaklık: {this.state.temps}
              }
    </Text>
    

    【讨论】:

    • 它写的是 8,我把它放在顶部,但我希望它从临时变量中设置状态变量
    • 您似乎没有在代码中调用 geoSuccess 函数,在您这样做之前,您声明临时文件不会更新
    • 我正在调用它,但我将其从那里删除,因为它太长了,获取经纬度和温度没有问题,我可以将它们写入控制台,但我可以' t 在文本中写入温度
    • ` geoLocate = (position) => { let geoOptions = { enableHighAccuracy: true, timeOut: 20000, maximumAge: 60 * 60, } this.setState({ready : false, error: null}) navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoFailure, geoOptions) } `
    【解决方案2】:

    根据代码观察,存在一些问题,我可以看到您在 geoSuccess 方法中设置状态后立即使用该状态。

    试试下面的代码

    export default class App extends React.Component {
        constructor(){
          super();
          this.state = {
            ready: false,
            where: {lat:null, lng:null, adr:null},
            error: null,
            temps: 8,
          }
          this.geoSuccess = this.geoSuccess.bind(this)
          this.geoFailure = this.geoFailure.bind(this)
        } 
        geoSuccess = (position) => {
          this.setState({
            ...this.state,
            ready:true,
          })
          let latit = position.coords.latitude
          let lonit = position.coords.longitude
          let latitStr = latit.toFixed(4)
          let lonitStr = lonit.toFixed(4)
          
          const options = {
            method: 'GET',
            url: `https://weatherapi-com.p.rapidapi.com/forecast.json?q=${latitStr},${lonitStr}`,
            headers: {
              'x-rapidapi-key': 'f7982bbb0dmsh562cc7597c785bbp1857b5jsn07695d566c0b',
              'x-rapidapi-host': 'weatherapi-com.p.rapidapi.com'
            }
          };
          axios.request(options).then(function (response) {
            let temp = response.data.current.temp_c
            this.setState({
              ...this.state,
              temps: temp
            })
          }).catch(function (error) {
            console.error(error);
          });
        }
        geoFailure = (err) => {
          this.setState({error: err.message})
        }
        render(){
          return (
              <Text style={styles.konum}>
              {
                  `Konumunuz Enlem: ${this.state.where.lat} Boylam: ${this.state.where.lng} Sıcaklık:${this.state.temps}`
              }
              </Text>
          );
        }
      }
    

    【讨论】:

    • undefined is not an object (evalating 'this.setState') 我得到这个错误它也不起作用:/
    • 我的答案已更新,请重试。
    • geoLocate = (position) =&gt; { let geoOptions = { enableHighAccuracy: true, timeOut: 20000, maximumAge: 60 * 60, } this.setState({ready : false, error: null}) navigator.geolocation.getCurrentPosition(this.geoSuccess, this.geoFailure, geoOptions) }
    • 这是地理定位功能,也许问题可能存在
    • 我也尝试了更新的但也没有工作
    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多