首页 文章

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

提问于
浏览
3

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

问题是我不知道如何判断 errorserrors 参数并且我已经在布局组件中对它进行了解析

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

我不知道这是否是将setState传递给另一个组件的正确方法 .

注意:我正在使用redux-promise-middleware它自己添加了_PENDING&_FULFILLED&_REJECTED .

src/actions/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/components/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/reducers/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/reducers/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 回答

  • 3

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

    所以代码应该变成:

    src/actions/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/components/layout.js

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

相关问题