簡體   English   中英

如何在 ReactJs 中使用 map 渲染字符串數組?

[英]How to render an array of strings using map in ReactJs?

我基本上想將數組中的每個字符串放在一個單獨的 div 中,我正在嘗試這樣做,但沒有呈現任何內容

export default class Loja extends Component {
      state = {
        loja: {},
        lojaInfo: {},
        category: []
      }

      async componentDidMount() {
        const { id } = this.props.match.params;

        const response = await api.get(`/stores/${id}`);

        const { category, ...lojaInfo } = response.data

        this.setState({ loja: category, lojaInfo });

        console.log(category)

      }

      render() {
        const { category } = this.state;


        return (

            <p>{category.map(cat => <div>{cat}</div>)}</p>

        );
      }
    }

console.log(category) 顯示:

在此處輸入圖片說明

錯誤是您正在更新componentDidMount兩個屬性,一個是loja: category ,第二個屬性是lojaInfo ,但在render()方法中,您正在訪問this.state.category ,它仍然是一個空字符串。

你想要做的是,在你的componentDidMount內部像這樣更新你的狀態:

this.setState({
  category,
  lojaInfo,
});

您已將您的category添加到該州的loja對象中。

這樣的事情應該工作:

async componentDidMount() {
    const { id } = this.props.match.params;
    const response = await api.get(`/stores/${id}`);
    const { category, ...lojaInfo } = response.data
    this.setState({ category, lojaInfo });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM