如何将setState传递给另一个组件

时间:2018-01-17 10:16:34

标签: javascript reactjs redux react-redux axios

我是React的新手我使用Redux& amp;构建了一个简单的应用程序反应。我只是尝试在Action.js文件中设置setState,然后在组件中使用它。

问题是我不知道如何向errors提供catch setState论证,我已经在布局组件中对此进行了分类

this.props.postUsers(this.state.username,this.state.password,this.state.errors)

我不知道这是否是将se​​tState传递给另一个组件的正确方法。

  

注意:我正在使用redux-promise-middleware它添加了_PENDING& _FULFILLED   &安培; _由它自己推荐。

的src /动作/ userActions.js

export function postUsers(username, password, errors) {
    let users = {
        username,
        password,
    };
    let self = this;
    return{
        type: "USERS_POST",
        payload: axios({
            method:'POST',
            url: url,
            data: users,
            contentType: 'application/json',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        })
            .then(success => {
                console.log('sucesssssssss', success)
            })
            .catch(({response}) => {
               self.setState({errors: response.data});
            })

    }
}

的src /组件/ layout.js

import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { postUsers } from '../actions/usersAction';

class Layout extends Component {
    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: '',
            errors: [],
        }
    }
    onUserUpdate(filed, event){
        if (filed === 'username') {
            this.setState({
                username: event.target.value
            });
        }
        if (filed ==='password') {
            this.setState({
                password: event.target.value
            });
        }
    }

    handlePostUsers(e){
        e.preventDefault();
        this.props.postUsers(this.state.username,this.state.password,this.state.errors)
    }
    render() {
        console.log('this.state.errors',this.state.errors);
        return (
            <div className="App">
                <input name="username" onChange={this.onUserUpdate.bind(this, 'username')}/>
                <input name="username" onChange={this.onUserUpdate.bind(this, 'password')}/>
                <button onClick={(e) => this.handlePostUsers(e)}>Go ahead</button>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        act: state.users,
    };
}

function matchDispatchToProps(dispatch) {
    return bindActionCreators({postUsers}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(Layout);

的src /减速器/ userReducers.js

const initalState = {
fetching: false,
fetched: false,
users: [],
error: []
};
export default function(state=initalState, action) {
    switch(action.type){
        case "USERS_POST_PENDING":{
            return {...state, fetching: true,}
        }
        case "USERS_POST_FULFILLED":{
              return {...state, fetching: false,fetched: true, users:[...state.users, action.payload],}
        }
        case "USERS_POST_REJECTED":{
            return {...state, fetching: false, error: action.payload,}
        }
        default:
            return state;
    }
}

的src /减速器/ index.js

import { combineReducers } from 'redux';
import usersReducer from './usersReducer';
import tweetsReducer from './tweetsReducer';
export default combineReducers({
    users: usersReducer,
    tweets: tweetsReducer,
})

的src / index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import promise from 'redux-promise-middleware';
import reducers from './reducers/index';
import { Provider } from 'react-redux';
import registerServiceWorker from './registerServiceWorker';

import Layout from './components/layout';


const store = createStore(reducers, applyMiddleware(promise(),thunk, logger,loadingBarMiddleware()));
const app = document.getElementById('root');

ReactDOM.render(
<Provider store={store}>
        <Layout />
</Provider>
    ,app);
registerServiceWorker();

1 个答案:

答案 0 :(得分:3)

我不确定您是否可以从组件外部设置组件的状态。 您应该将handle函数从layout.js传递给userActions.js

所以代码应该成为:

<强>的src /动作/ userActions.js

export function postUsers(username, password, errors, errorFunction) {
let users = {
    username,
    password,
};
let self = this;
return{
    type: "USERS_POST",
    payload: axios({
        method:'POST',
        url: url,
        data: users,
        contentType: 'application/json',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
        .then(success => {
            console.log('sucesssssssss', success)
        })
        .catch(({response}) => {
           errorFunction(response.data);
        })

    }
}

<强>的src /组件/ layout.js

    ...
        handlePostUsers(e){
    e.preventDefault();
    this.props.postUsers(
        this.state.username,
        this.state.password,
        this.state.errors,
        (responseData)=>{this.setState({errors: responseData})
        });
}
    ...