javascript - ReactJS 和 Redux 从另一个文件访问状态 "constructor"

标签 javascript reactjs redux react-redux

我只是想发布一个数据,如果我将获取函数放在同一个文件中,一切正常,但是当我将其移动到另一个文件时,它显示无法读取属性,我尝试了 this.props 而不是 this。状态,我如何将此文件连接到构造函数()

enter image description here

scr/component/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(){
    super() 
    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></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 type="simpleQuery" onClick={this.props.postUsers.bind(this)}>Add News</button>
    
            <table>
                <thead>
                <tr>
                      <th>Name</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);

src/actions/userAction.js

export const fetchUsers = (data) =>{
            return{
            type: "USERS",
            payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
                
            })
            .then(res => res.json())
    }
};
export const postUsers = (event) =>{
    let users = {
        name: this.state.name,
        age: this.state.age
    }
    return{
            type: "USERS_POST",
            payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(users),
            })
            .then(res => res.json())
    }
};

src/reducers/userReducer.js

const initalState = {
fetching: false,
fetched: false,
users: [],
error: null
};
export default function(state=initalState, action) {
    let newState = Object.assign({}, state);
    switch(action.type){
        case "USERS_PENDING":{
            return {...state, fetching: true,loading: false,}
        }
        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 newState;
        }
        case "USERS_POST_REJECTED":{
            return {...state, fetching: false, error: action.payload,}
        }
        default:
            return state;
    }
}

如果我遗漏了任何信息,请告诉我。

如果已经有人问过这个问题,如果您能够为我指明正确的方向,我将不胜感激。

非常感谢!

最佳答案

您需要将该数据传递给您的 postUsers() 函数。

<button 
  type="simpleQuery" 
  onClick={() => this.props.postUsers(this.state.name,this.state.age)}
>Add News</button>

然后在您的 postUsers() 函数中应该接受这些参数:

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

关于javascript - ReactJS 和 Redux 从另一个文件访问状态 "constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198502/

相关文章:

javascript - 如何从 JS 更改动态 CSS 类的 bg 颜色

reactjs - 无法导出带有 getServerSideProps 的 nextjs 页面

redux - componentWillReceiveProps 状态与 redux 状态更新后的渲染状态不同

javascript - 基于文本使用 Jquery 选择选项

javascript - 如何在mongoDB中删除-nodejs

javascript - JSON 文件仅在函数中加载,但一旦完成,加载的数据就会在 React 中消失

javascript - 如何映射从数据库中获取的元素?

reactjs - addEventListener 通过映射调度来 react redux

javascript - 在连接到状态不同部分的不同路由上重用 react/redux 组件

javascript - EmberJS 如何从 Controller 属性的选择菜单中创建选项