【问题标题】:React- Map function in component doesn't workReact-组件中的地图功能不起作用
【发布时间】:2018-04-13 23:29:36
【问题描述】:

我正在处理一个小型应用程序,我在其中使用 react.js。由于我是初学者,因此我遇到了一些问题。

我想映射我的数组,但它不起作用。我遵循了一个 youtube 教程,不同之处在于该数组填充了硬编码数据。我正在获取我的数据并在获取完成后将其添加到数组中。 (JSON 对象)。

import React from "react";
import Product from "./Product"

export default class ProductList extends React.Component{
render()
{ console.log("productlist")

    return (
     <ul>
     {this.props.products.map((product, i) => 
        { return <Product product={product} key={i}/>  })}
        {console.log("test")}
    </ul> 
     )

}
}

console.logs 有效,但 map-function 无效。我尝试过不使用 ID,并且以不同的方式尝试过,但它不起作用。我希望数据传递到我的最后一个组件中,称为 Product。我想要填充我的 元素。

当我刚刚将“this.props.products”传递给“”时,我到达了 Product 组件,但没有数据填充。 从“反应”导入反应;

export default class Product extends React.Component{
render(){
    console.log("product")

    return (   
  <li> {this.props.product.title} {this.props.product.price} <img src={this.props.product.imageUrl}/> </li>
    )
}
}

我正在使用 fetch 方法从 Json 文件中获取数据。

fetch('http://localhost:8080/products')
.then(
response =>
  response.ok
    ? response.json()
    : Promise.reject(Can't communicate with REST API server (${response.statusText})`),
)
.then(products => {
    products.forEach(product => productArray.push(product));
})

正如您在上面看到的,我正在将 Jsonfile 中的产品添加到我创建的数组中。而且我不确定这是否是导致我的问题的原因。

import React from "react";
import ReactDOM from "react-dom";
import Container from "./Components/Container";

let productArray = []; 
const app = document.getElementById('app');
ReactDOM.render(<Container products={productArray}/>, app)

我正在使用 ReactDOM.render 将我的数组传递到我的 Container.js 文件中。 在 Container.js 文件中,我还从 react 导入 React 并从 ./Productlist 导入 ProductList。所以我继续传递数组(并且我检查了它是否有值,并且有。

  <ProductList products = {this.props.products}/>

【问题讨论】:

    标签: arrays reactjs return components map-function


    【解决方案1】:

    这是因为 products 在您的 fetch 请求完成时已过时。即使您正在更新它(productArray.push),您的组件也不知道此类更改。更不用说这是一个糟糕的模式。

    为此,请使用适当的 React 组件 lifecycle 方法和 state 处理。

    在您的Container 组件中:

    const Container extends React.Component {
      constructor(props) {
        super(props)
    
        this.state = {
          products: [], // Initialize product as an empty array
        }
      }
    
      componentDidMount() {
        fetch('http://localhost:8080/products')
          .then(response =>
            response.ok
              ? response.json()
              : Promise.reject(`Can't communicate with REST API server (${response.statusText})`),
          )
          .then(products => {
            this.setState({ products }) // Notify your component that products have been fetched
          })
      }
    
      render() {
        return (
          <div>
             ...
            <ProductList products={this.state.products} />
          </div>
        )
      }
    }
    

    请不要说setState may be asynchronous。如果您将来获取新数据,请不要犹豫使用@Luke M Willis 指出的此类功能:

    this.setState(prevState => ({
      products: [ ...prevState.products, ...products ],
    }))
    

    【讨论】:

    • 要将新获取的产品附加到状态,请使用函数式setState:.then(products =&gt; this.setState(prevState =&gt; ({ products: [ ...prevState.products, ...products ] })))
    • 通过查看他的代码,看起来这个请求不会运行多次。另外,我会为此使用redux。我不喜欢直接在组件中管理状态 :)
    • 我同意这个例子,但我们看不到fetch 当前被调用的位置。它可能是响应点击或其他机制而发生的。另外,我同意这种状态在 redux 中是合适的——不过,我认为 there is a case for using component state 在使用 redux 的应用程序中是合适的。此外,在开始使用 React 时,redux 可能会使学习过程过于复杂。
    • 我完全同意你的看法。这就是为什么我在回答中根本没有提到 redux。我可以指出setState 也是异步的,没问题:D
    • 构造函数初始化state,以便您稍后可以通过this.setState(...)更新它
    【解决方案2】:

    @MissAndersson 你在哪里调用你的 fetch 函数?

    如果您在 React 组件之外调用 fetch 函数,那可能就是问题所在。您的 React 组件未正确重新渲染。

    React 组件在其状态或道具发生变化时重新渲染。请参阅此 CodeSandbox 示例。 (https://codesandbox.io/s/812yv7wjrl)

    我的 fetch 函数会更新组件的状态,这会强制重新渲染。

    【讨论】:

    • 我在我的组件之外调用 fetch 函数。 fetch 函数位于 index.js 文件中,我在其中使用“reactdom.render(Container ....)”并创建数组。我会试着移动它。感谢您的提示
    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 2021-10-10
    • 1970-01-01
    • 2022-06-11
    • 2019-09-01
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多