简体   繁体   English

React&Redux Reducer不会改变

[英]React & Redux Reducer not changin

I have a React app built using Redux and React I'm trying to post data. 我有一个使用Redux和React构建的React应用,我正在尝试发布数据。 Everything works fine, but I don't know why the reducer doesn't return the action. 一切正常,但是我不知道为什么减速器不返回动作。 Does that make sense if I render fetch function after post function? 如果在post函数之后渲染fetch函数,那有意义吗? I don't think react works like this way. 我不认为React这样工作。

scr/actions/userAction.js SCR /动作/ userAction.js

export function fetchUsers(data) {
            return{
            type: "USERS",
            payload: fetch('http://rest.learncode.academy/api/johnbob/users',{
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }

            })
            .then(res => res.json())
    }
};

export function postUsers(name, age) {
let users = {
    name,
    age
}
    return{
            type: "USERS_POST",
            payload: fetch('http://rest.learncode.academy/api/johnbob/users',{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(users),
            })
            .then(res => res.json())

    }

};

src/reducers/userReducer.js SRC /减速器/ userReducer.js

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

src/components/layout.js SRC /组件/ layout.js

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


class Layout extends Component {
constructor(props){
    super(props) 
    this.state = {  
        name: '',
        age: ''}
}

onUserUpdate(filed, event){
    //console.log('onUserUpdate: ' + filed + '==' + event.target.value);
    if (filed === 'name') {
        this.setState({
            name: event.target.value
        })
        return
    }
    if (filed ==='age') {
        this.setState({
            age: event.target.value
        })
        return
    }
}

componentDidMount() {  
  this.props.fetchUsers();
}
  render() {
    const { act } = this.props;

      const fetchUserss = act.users.map(d =>  <tr key={d.id}><td>{d.name}</td><td>{d.age}</td><td></td></tr>);

    return (
      <div className="App">
        <label>
            name:
              </label>
            <input type="text" name="name" onChange={this.onUserUpdate.bind(this, 'name')} placeholder="Enter Name"/>
                <label>
                age:
              </label>
                <input type="text" name="age" onChange={this.onUserUpdate.bind(this, 'age')} placeholder="enter username"/>
                <button onClick={() => this.props.postUsers(this.state.name,this.state.age)}>Add News</button>
            <table>
                <thead>
                <tr>
                 <th>Name</th>
                  <th>age</th>
                </tr>
                </thead>
                <tbody>
                 {fetchUserss}
                </tbody>
            </table>
        </div>
    );
  }
}



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

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

Please let me know if I miss out any information. 如果我错过任何信息,请告诉我。

If this has already been asked, I would greatly appreciate if you are able to point me in the right direction. 如果已经问过这个问题,如果您能指出正确的方向,我将不胜感激。

Thank you so much! 非常感谢!

your switch case looks weird: 您的开关盒看起来很奇怪:

case "USERS_FULFILLED":{
    return {...state, users: action.payload}
}

case "USERS_POST_FULFILLED":{
    return action.payload;
}
case "USERS_POST_DELETE_FULFILLED":{
    return {...state, users: action.payload}
}

why do you use brachets? 为什么要使用Brachets? it should be: 它应该是:

switch (action.type) {
   case 'USERS_FULLFILED':
       return { ...state, users: action.payload };
}

I found the solution from the example of @Luis Nolazco It's really helped me, I should put action.payload into square brackets 我从@Luis Nolazco的示例中找到了解决方案,这确实对我有帮助,我应该将action.payload放在方括号中

case "USERS_POST_FULFILLED":{
          return {...state, fetching: false,fetched: true, users:[...state.users, action.payload],}
    }

here's the example codesandbox.io/s/MQZWLJloA by @Luis Nolazco 这里的例子codesandbox.io/s/MQZWLJloA通过@Luis Nolazco

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM