繁体   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