reactjs - 当元素的长度达到this.state中的limit时禁用按钮

问题描述 投票:0回答:2

但是在componentDidMount中进行ajax调用之前,元素不会被填充

看起来渲染发生在ajax调用返回之前,因此按钮永远不会被禁用。如何确保按钮被正确禁用?

码:

<button className="someclass" onClick={this.handleClick} disabled={this.state.apps.length < 5}>some text</button>}

componentDidMount

componentDidMount() {
    fetch("some_url", {
        method: 'post',
        body: JSON.stringify({"user": "some email"}),
        headers: {'Content-Type': ' application/json'}
    })
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({apps: JSON.parse(result)});
        },
        (error) => {
            console.log("error", error);
        }
        );
}

调用并返回元素apps没有问题,但是时间使禁用没有发生

编辑:我的逻辑错了....应该检查>=而不是< .......我是傻.......

reactjs
2个回答
0
投票

再看一下,问题可能与解析数组有关。你为什么解析它?它不适用于数组。只需定期设置您的州:

this.setState({apps: result});

class App extends React.Component {
  state = {
    apps: [],
  }

  componentDidMount() {
    fetch( "https://jsonplaceholder.typicode.com/posts" )
      .then( res => res.json() )
      .then( apps => {
        this.setState({ apps })
      })
  }
  render() {
    return (
      <div>
        <button
          onClick={this.handleClick}
          disabled={this.state.apps.length >= 5}
        >some text</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

0
投票

你必须在构造函数中初始化应用程序

constructor() { 
    this.state = {apps: ''};
  }
© www.soinside.com 2019 - 2024. All rights reserved.