【问题标题】:Pass fetch data to components using useState React Native使用 useState React Native 将获取数据传递给组件
【发布时间】:2020-06-01 20:14:29
【问题描述】:

我是 React Native 的新手。实际上这是我的第一个应用程序。

我一直在尝试将数据从 Fetch 传递到组件,但没有运气。我上下左右研究了谷歌,尝试了数百万种方法,但仍然没有成功。

这是我的 App.js

import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';

import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';

const authorization = { authorization: '1234aa' };

export default function App() {
  const [fetchApiData, setApiData] = useState();

  useEffect(() =>
  fetch('https://example.com/get-app-home.php', {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(authorization),
  })
  .then(res => res.json())
  .then(res => {
    this.setState({ setApiData: res })
  })
  .catch(() => this.setState({ hasErrors: true }))
  );
  return (
    <View style={styles.viewport}>
      <Header />
      <ScrollView style={styles.contentHolder}>
        <Index content={fetchApiData}/>
      </ScrollView>
    </View>
);


}

这是我的 index.js 文件

import React from 'react';
import { View, Text } from 'react-native';

import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'

const Index = props => {

    return (
      <View>
        <BigNews
        image={props.content.first.image}
        pretitle={props.content.first.pretitle}
        title={props.content.first.title}
        introduction={props.content.first.introduction}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>
      </View>
    );
}
export default Index;

我经常收到 TypeError: undefined is not an object (evalating 'props.content.first')

我尝试了数百万种方法,但大多数时候这是我看到的错误。如果我执行 console.log of state 我会得到未定义或空的。

【问题讨论】:

    标签: javascript react-native react-hooks fetch-api use-state


    【解决方案1】:

    在您的Index 组件中,content 属性最初是未定义的,因为您没有将任何值(通常称为“初始状态”)传递给您的useState 组件中的useState 函数。

    请尝试:

    const [ fetchApiData, setApiData ] = useState({
        first: {},
        second: {}
    });
    

    请注意,我已经使用 first 和 second 项填充了初始状态,因为尝试访问树下方的元素(image、pretitle 等)仍然会引发错误.

    【讨论】:

    • 好的,你解决了一个问题。现在我得到了错误:TypeError:destroy is not a function (In destroy(),destroy is an instance of Promise)
    • @Korovjov 听起来像是另一个问题的原因。具体一点。
    • 这是具体的。那是错误。而已。 ibb.co/YN5F4x3
    • 好的,我明白了,问题在于 Fetch API 中的异步等待。我必须创建异步功能。有没有什么方法可以实现这一点(您提出第一个 {},第二个 {}),而无需手动输入 first、second 等……我的意思是还有其他方法吗?
    【解决方案2】:

    您没有设置您的数据this.setState 用于类组件。将this.setState 替换为setApiData()。

    useState 返回初始状态和更新该值的函数。

    const [ hasError, setHasErrors] = useState(false);
    
    .then(res => res.json())
    .then(res => {
      setApiData(res)
    })
    .catch(() => setHasErrors(true))
    );
    

    正如乔治指出的那样,初始状态设置为空,执行props.content.first.image 将导致错误。将初始值设置为像

    这样的对象
    const [ fetchApiData, setApiData ] = useState({
       first: {},
       second: {}
    });
    

    或验证组件中的值。

    const Index = props => {
    
      return (
       <View>
        <BigNews
        image={props && props.content && props.content.first && props.content.first.image}
        pretitle={props && props.content && props.content.pretitle && props.content.first.pretitle}
        title={props && props.content && props.content.title && props.content.first.title}
        introduction={props && props.content && props.content.introduction && props.content.first.introduction}
        style={{color: props && props.content && props.content.first && props.content.first.mark}}/>
    
        ...
      </View>
      );
    }
    export default Index;
    

    【讨论】:

    • @Korovjov 请注意,虽然这不是您遇到错误的原因,但它仍然适用。
    • TypeError: undefined is not an object (evalating 'props.content.first')
    • 乔治关于状态的回答,正如你所指出的,是正确的。那里没问题。但是现在 React 抛出一个错误 TypeError destroy is not a function。而且我在 Google 上根本找不到那个错误。
    猜你喜欢
    • 2019-06-18
    • 2019-01-18
    • 2021-09-16
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多