如何在ReactJs中使用map渲染字符串数组?

时间:2019-12-10 01:22:08

标签: javascript arrays reactjs jsx

我基本上想将数组中的每个字符串放在一个单独的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(类别)显示以下内容:

enter image description here

2 个答案:

答案 0 :(得分:1)

错误是您要更新componentDidMount内的2个属性,一个是loja: category,第二个属性是lojaInfo,但是在render()方法中,重新访问this.state.category,它仍然是一个空字符串。

相反,您想做的是在componentDidMount内部更新状态,如下所示:

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

答案 1 :(得分:1)

您已将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 });
}