当react组件状态发生变化时,将调用render方法.因此,对于任何状态更改,可以在呈现方法主体中执行操作.那么setState回调是否有特定的用例?
我想问一下当我做onclick事件时为什么我的状态没有改变.我刚才搜索过我需要在构造函数中绑定onclick函数,但状态仍未更新.这是我的代码:
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import BoardAddModal from 'components/board/BoardAddModal.jsx';
import style from 'styles/boarditem.css';
class BoardAdd extends React.Component {
constructor(props){
super(props);
this.state = {
boardAddModalShow: false
}
this.openAddBoardModal = this.openAddBoardModal.bind(this);
}
openAddBoardModal(){
this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
console.log(this.state.boardAddModalShow);
}
render() {
return (
<Col lg={3}>
<a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
<div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
Create New Board
</div>
</a>
</Col> …Run Code Online (Sandbox Code Playgroud) class SomeClass extends Component{
someEventHandler(event){
}
render(){
return <input onChange={------here------}>
}
}
Run Code Online (Sandbox Code Playgroud)
我看到不同版本的------here------部分.
// 1
return <input onChange={this.someEventHandler.bind(this)}>
// 2
return <input onChange={(event) => { this.someEventHandler(event) }>
// 3
return <input onChange={this.someEventHandler}>
Run Code Online (Sandbox Code Playgroud)
版本有何不同?或者只是一个偏好问题?
谢谢大家的回答和评论.都是有帮助的,我强烈建议阅读此链接FIRST如果你是这个困惑了我.
http://blog.andrewray.me/react-es6-autobinding-and-createclass/
我正在阅读反应生命周期,我感到有点困惑.有人建议使用componentWillMount进行ajax调用:
在componentDidMount中调用setState将触发另一个render()调用,它可能导致布局颠簸.
而在其他地方,它说不要在componentWillMount中放置ajax调用:
https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d
...在调用初始渲染之前,此函数最终可能会被多次调用,因此可能会导致触发多个副作用.由于这一事实,不建议将此功能用于任何引起副作用的操作.
哪个是对的?
为什么我的状态未定义?我尝试了各种解决方案,但没有一个适合我.有人能指出这里做错了什么
编辑:
完整的组件代码
class Sidebar extends React.Component {
constructor (props) {
super(props)
this.state = {
menuSelected: menuOptions.menuItems[0].title,
}
this.createMenuListItem = this.createMenuListItem.bind(this)
}
render () {
console.log(this.state.menuSelected)
function getChildItems (child) {
let childItems = child.children.map(function (menuItem, index) {
return createMenuListItem(menuItem)
})
return (
<li key={child.title} className='dropdown'>
<i className={child.iconName} />
<span className='dropdown-toggle'>{child.title}</span>
<ul className=''>
{childItems}
</ul>
</li>
)
}
function createMenuListItem (menuItem) {
if (menuItem.hasChild === 'N') {
console.log(this.state.menuSelected)
return (
<li key={menuItem.title}>
<a href='#'>
<i className={menuItem.iconName} />
<span>{menuItem.title}</span>
</a>
</li>
) …Run Code Online (Sandbox Code Playgroud)