但是在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
没有问题,但是时间使禁用没有发生
编辑:我的逻辑错了....应该检查>=
而不是<
.......我是傻.......
再看一下,问题可能与解析数组有关。你为什么解析它?它不适用于数组。只需定期设置您的州:
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>
你必须在构造函数中初始化应用程序
constructor() {
this.state = {apps: ''};
}