React使用this.handleVote = this.handleVote.bind(this)的含义

this.handleVote = this.handleVote .bind(this)
此时的this指向新生成的实例,赋值语句右侧的表达式**this.handleVote .bind(this)**会首先找到this.handleVote()这个方法,由对象的属性查找机制(沿原型链由近及远查找)可知此处会查找到原型方法this.handleVote ( ),接着执行bind(this),此处的this指向新生成的实例,所以赋值语句右侧的表达式计算完成后,会生成一个指定了this的新方法,接着执行赋值操作,将新生成的函数赋值给实例的handleVote 属性,由对象的赋值机制可知,此处的handleClick会直接作为实例属性生成。
总结一下,也就是说上面的语句做了一件这样的事情:

把原型方法handleVote ( )改变为实例方法handleVote ( ),并且强制指定这个方法中的this指向当前的实例。

React使用this.props.dispatch调用后端接口,也需要借助redux-thunk中间件来处理异步操作。下面是一个简单的例子: ```javascript // 定义一个异步action creator export const fetchData = () => { return async (dispatch) => { dispatch({ type: 'FETCH_DATA_REQUEST' }); try { const response = await fetch('/api/data'); const data = await response.json(); dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }); } catch (error) { dispatch({ type: 'FETCH_DATA_FAILURE', payload: error }); } }; } // 在组件中使用dispatch调用异步action creator import { connect } from 'react-redux'; import { fetchData } from './actions'; class MyComponent extends React.Component { componentDidMount() { // 调用异步action creator this.props.dispatch(fetchData()); } render() { // 根据store中的状态渲染组件 const { isLoading, data, error } = this.props; if (isLoading) { return <div>Loading...</div>; } else if (error) { return <div>Error: {error.message}</div>; } else { return ( <div> <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } } } const mapStateToProps = state => ({ isLoading: state.isLoading, data: state.data, error: state.error, }); export default connect(mapStateToProps)(MyComponent); ``` 在上面的例子中,fetchData是一个异步action creator,它返回一个函数,这个函数接收一个参数:dispatch。在函数内部,我们可以使用dispatch方法来分发多个同步action,以更新store中的状态。在组件中,我们通过connect函数将store中的状态映射为props属性,然后在componentDidMount中使用this.props.dispatch调用该方法,以触发异步操作。当异步操作完成后,根据store中的状态渲染组件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值