gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:30:07 24 4
gpt4 key购买 nike

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

问题是我不知道如何将 errors 参数定义为 catch setState 并且我已经像这样在布局组件中定义了它

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

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

Note: I'm using redux-promise-middleware it adds _PENDING & _FULFILLED & _REJECTED by it's own.

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();

最佳答案

我不确定您是否可以从组件外部设置组件的状态。您可能应该将 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})
});
}
...

关于javascript - 如何将 setState 传递给另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com