【问题标题】:Making axios call in render does not return anything在渲染中进行 axios 调用不会返回任何内容
【发布时间】:2021-08-28 18:22:22
【问题描述】:

我正在我的 react native 应用程序的渲染中进行 axios 调用。

render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={{justifyContent: 'center'}}>
          <Text style={styles.heading}>Checked Out Books</Text>
          {this.state.books.map((book) => {
            axios
              .get('http://localhost:3000/books/id/' + book)
              .then((res) => {
                console.log(res.data);
                return (
                  <View>
                    <Image
                      source={{uri: res.data.cover}}
                      height={150}
                      width={110}></Image>
                    <Text>{res.data.title}</Text>
                  </View>
                );
              })
              .catch((err) => {
                console.log(err);
                alert('Something went wrong.');
              });
          })}

当调用完成并进入返回步骤时,没有返回任何内容。

我不知道为什么会这样。 这段代码没有返回:

<View>
  <Image
      source={{uri: res.data.cover}}
      height={150}
      width={110}></Image>
      <Text>{res.data.title}</Text>
</View>

这是为什么?

【问题讨论】:

  • 你没有在map返回任何东西
  • 哦,我该怎么做呢?对不起,我是新来的原生反应

标签: javascript react-native axios jsx


【解决方案1】:

根据您没有从 .map() 返回任何内容的评论,arrow function 要么不需要像 (book) =&gt; axios.get( 这样的括号,要么有括号并使用单词 return(book) =&gt; { return axios.get(

您正在查看的带有&lt;View&gt; 元素的return 语句是return 用于.then() 回调函数,而不是整个.map() 函数。

但这不会解决您的问题,因为您将从.map() 返回的值是Promise,这不是您可以在组件中打印出来的值JSX。

@jamielarchin 是正确的,您不能在 render() 方法中进行数据提取。它需要在 componentDidMountcomponentDidUpdate 之类的生命周期方法内,或者在 useEffect 挂钩内。由于你是刚学习,我建议你使用最新的方法来学习,即使用函数组件和useEffect

我建议您在单独的Book 组件中处理每本书的数据获取,而不是在循环中处理获取数据。这要简单得多,而且如果只有一本书发生变化,它就不必重新获取整个列表。

您可以将Book 组件设为函数组件,并将当前的“图书列表”组件保留为类组件。

// the book id is the only prop
const Book = ({ id }) => {
  const [isError, setIsError] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  // save the book data here, once loaded
  const [data, setData] = useState();

  useEffect(
    () => {
      setIsLoading(true);
      axios
        .get('http://localhost:3000/books/id/' + id)
        .then((res) => setData(res.data))
        .catch((err) => setIsError(true))
        .finally(() => setIsLoading(false));
    },
    [id] // dependency on the book id
  );

  if (data !== undefined) {
    return (
      <View>
        <Image source={{ uri: data.cover }} height={150} width={110}></Image>
        <Text>{data.title}</Text>
        )}
      </View>
    );
  }
  // can show loading and error components too
  // but for now I'm just returning nothing
  return null;
};
render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={{justifyContent: 'center'}}>
          <Text style={styles.heading}>Checked Out Books</Text>
          {this.state.books.map((book) => <Book id={book} key={book}/>)}

【讨论】:

    【解决方案2】:

    您不应该在渲染中进行 axios 调用(可以进行一些调整,但这不是一个好习惯)。如果您在功能组件中,则应该使用钩子(如 useEffect),如果您在类组件中(我假设您是),则应使用 componentDidMount。示例如下所示。

    class App extends React.Component {
      constructor(){
        this.state = {
            bookIds: [], //You would fill this beforehand
            books: [],
          }
      }
    
      componentDidMount(){
        for(let i = 0; i < bookIds; i++){
          axios.get('http://localhost:3000/books/id/' + bookIds[i]).then((res) => {
             books.push(res); 
           }.catch((err) => {
               console.log(err);
               alert('Something went wrong.');
          });
        }
      }
    
    
      render() {
        return(
            <View style={{flex: 1, backgroundColor: 'white'}}>
            <ScrollView
              style={styles.scrollView}
              contentContainerStyle={{justifyContent: 'center'}}>
              <Text style={styles.heading}>Checked Out Books</Text>
              {this.state.books.map((book) => {
                 return (
                   <View>
                     <Image
                       source={{uri: book.data.cover}}
                       height={150}
                       width={110}>
                     </Image>
                     <Text>{book.data.title}</Text>
                   </View>
                );
            })
          }
        );
      }
    }
    

    建议你看看这个:https://reactjs.org/docs/state-and-lifecycle.html

    括号可能有一些问题,祝你有美好的一天!

    【讨论】:

      【解决方案3】:

      应该从类组件的生命周期方法中获取数据。您可能想使用 componentDidMount:https://reactjs.org/docs/react-component.html#componentdidmount

      【讨论】:

        猜你喜欢
        • 2018-09-05
        • 2021-04-20
        • 2018-04-05
        • 2021-01-01
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 2022-08-23
        • 1970-01-01
        相关资源
        最近更新 更多