简体   繁体   English

JSX 组件不呈现状态图

[英]JSX component doesn't render map of state

i'm trying to make a list when users selects their fav links onClick ...当用户在点击时选择他们最喜欢的链接时,我正在尝试列出一个列表...

Any idea why this doesn't work?知道为什么这不起作用吗? it will push values to state.array in console.log but JSX will not render in ul.li它会将值推送到 console.log 中的 state.array 但 JSX 不会在 ul.li 中呈现

import React, { Component } from "react";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      link: {
        name: "",
        type: "",
        size: "",
        tests: []
      },
      tests: ["1", "2", "3", "4"]
    };
  }

  componentDidMount() {
    console.log(this.state);
  }

  onClick = e => {
    const linktests = this.state.link.tests;
    console.log("clicked");

    linktests.push(e.target.innerText);
    console.log("link tests : " + linktests);
  };
  render() {
    const { link, tests } = this.state;
    const linktests = this.state.link.tests;
    return (
      <div>
        <div id="link">
          {linktests.map(stuff => (
            <ul>
              <li> {stuff} </li>
            </ul>
          ))}
        </div>
        <br></br>
        {tests.map(stuff => (
          <ul>
            <li onClick={this.onClick} value={stuff}>
              {stuff}
            </li>
          </ul>
        ))}
      </div>
    );
  }
}

hope someone can help :D <3 thanks希望有人可以帮助:D <3 谢谢

You need to set the new links to the state.您需要将新链接设置为状态。 Also use concat or slice on the original state array to avoid mutating it directly.还可以在原始状态数组上使用concatslice以避免直接对其进行变异。

 onClick = e => {
    const linktests = this.state.link.tests.concat();
    console.log("clicked");

    linktests.push(e.target.innerText);
    this.setState({link: { ...this.state.link, tests: linktests});
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM