【问题标题】:How to render an array of strings using map in ReactJs?如何在 ReactJs 中使用 map 渲染字符串数组?
【发布时间】:2020-04-03 03:32:22
【问题描述】:

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

【问题讨论】:

  • 您没有更新此行中状态的类别部分this.setState({ loja: category, lojaInfo });
  • 抱歉我有点新反应你能在代码中显示吗?
  • state 中的字段类别始终为空数组。

标签: javascript arrays reactjs jsx


【解决方案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 });
}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2022-01-15
      • 2016-02-02
      • 2019-12-04
      • 2023-01-20
      • 2014-08-17
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多