ReactJS& Redux从另一个文件访问状态“构造函数”

时间:2018-01-11 01:12:25

标签: javascript reactjs redux react-redux

如果我将fetch函数放在同一个文件中,但是当我将其移动到另一个文件时,我只是试图发布一切正常的数据,但是当我将它移动到另一个文件时,它显示无法读取属性,我尝试过this.props而不是这个。 state,如何将此文件连接到constructor()

enter image description here

SCR /组件/ 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 /动作/ 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 /减速器/ 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;
    }
}

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

如果已经提出这个问题,如果你能指出我正确的方向,我将不胜感激。

非常感谢你!

3 个答案:

答案 0 :(得分:2)

我们无法访问组件外的状态。您可以将状态变量params传递给postUsers函数。

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

在你的postUsers函数中

export const postUsers = (name,age) =>{
let users = {
    name: name,
    age: 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())
}

};

答案 1 :(得分:2)

您需要将该数据传递给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())
});

答案 2 :(得分:1)

我可以看到你试图将范围绑定到箭头函数。你不能这样做。箭头功能没有范围。

相反,你应该写一个普通的函数。

let postUsers = function() {};

function postUsers(){}

换句话说,箭头函数内的this始终从父函数继承。因此,在您的情况下,this不是undefined,但它不是您期望的this