React 开发中应该注意的小问题

React 表单的绑定

每个表单组件都用onChange绑定

<form onSubmit={this.onSubmit}>
    <h1>Welcome Join commmit</h1>
    <div className="form-group">
        <label className="control-label">Username</label>
        <input type="text" name="username" value={this.state.username} onChange={this.onChange} className={classnames('form-control', { 'is-invalid' : errors.name==='username' })} placeholder="please input username" />
    </div>
</form>

onChange 的操作

onChange =  (e)  =>  { 
        this.setState({
            [e.target.name]: e.target.value
        })
    }

redux-thunk 的使用

actions里面的actionCrator

export const registerRequest = (paramas) => {
    return dispatch => {
        return axios.post('/api/user',paramas);
    }
}

async await 异步方法的使用

export const loginRequest = (paramas) => {
    return async(dispatch) => {
        const result = await axios.post('/api/user/login', paramas);
        dispatch(loginAction(result.data))
        return result
    }
}

容器组件里面mapStateToDispatch()

import * as useAction from '../'

用bindActionCreators()封装 action 方便action的操作

const mapDispatchToProps = (dispatch) => ({
    useAction: bindActionCreators(useAction,dispatch)
})

内容里面使用的方法

onSubmit = (e) => {
        e.preventDefault()
        this.setState({ isLoading: true })
        this.props.useAction.registerRequest(this.state).then(({ data }) => {
            if (data.code === 0) {
                this.setState({
                    errors: data,
                })
            }
            this.setState({
                isLoading: false
            })
            localStorage.setItem('SYSTEM_USER', JSON.stringify(data))
            this.props.history.push('/');
        })
     }

注意: 如果 UI组件没有在路由router管理里面。 props里面是取不到history对象的。解决的办法
1、在UI组件里面传父组件的history对象给UI 子组件 。
2、从 react-router-dom里面引入 withRouter高阶组件包裹UI组件。就可以拿到history对象了。

在UI组件里面传父组件的history对象给UI 子组件

<ChildUIComponent  history={this.props.history }/>

从 react-router-dom里面引入 withRouter高阶组件包裹UI组件

import withRouter from 'react-touter-dom'
export default (withRouter)(ChildUIComponent)

redux_devTools_extension 插件的配置

const composeEnhancer = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
原文地址:https://www.cnblogs.com/boyGdm/p/14139217.html