React-redux:为什么在Home组件中状态未定义?

时间:2019-05-22 09:18:46

标签: react-native react-redux

我无法在HomeComponent.js中获取状态。每次尝试打印时,它都会返回“ undefined”。

我尝试了多种方法来调用Home组件中的onPress(例如onPress = {this.printState()},但没有用)

这是我的HomeComponent.js

//import statements

const mapStateToProps = state => {
    return {
    jobTitles: state.jobTitles
}
}

const mapDispatchToProps = dispatch => ({
    fetchJobTitles: () => dispatch(fetchJobTitles())
});

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            jobInputValue: '',
            addressInputValue: ''
         };
      }


componentDidMount() {
    this.props.fetchJobTitles();
}

printState = () => {
    console.log('State is: ' + 
    JSON.stringify(this.state.jobTitles));
}

render() {
    return (

    <ImageBackground style={styles.bkgImage} source={require('../assets/homepage_background.jpg')}>

      //JSX goes here

        <Button 
            title="CAUTĂ"
            type="outline"
            underlayColor={colors.red}
            titleStyle={styles.buttonTitleStyle}
            color={colors.red}
            style={styles.buttonStyle}
            onPress={this.printState}
            />
    </ImageBackground>
    );
  }
}


//some styles

export default connect(mapStateToProps, mapDispatchToProps)(Home);

这是我的减速器(jobTitles.js):

import * as ActionTypes from '../ActionTypes';

export const jobTitles = (state = { errMess: null,
                             jobTitles:[]}, action) => {

switch (action.type) {
    case ActionTypes.GET_JOB_TITLES:
        return {...state, errMess: null, jobTitles: action.payload};

    case ActionTypes.JOB_TITLES_FAILED:
        return {...state, errMess: action.payload};

    default:
      return state;
  }

};

这是我的动作创建者:

import * as ActionTypes from './ActionTypes';
import { baseUrl } from '../shared/baseUrl';

export const fetchJobTitles = () => (dispatch) => {

return fetch(baseUrl + 'api/jobs/job_keywords')
.then(response => {
    if (response.ok) {
      return response;
    } else {
      var error = new Error('Error ' + response.status + ': ' +     
response.statusText);
          error.response = response;
          throw error;
        }
      },
      error => {
            var errmess = new Error(error.message);
            throw errmess;
      })
    .then(response => response.json())
    .then(jobTitles => dispatch(addJobTitles(jobTitles)))
    .catch(error => dispatch(jobTitlesFailed(error.message)));
};

export const jobTitlesFailed = (errmess) => ({
    type: ActionTypes.JOB_TITLES_FAILED,
    payload: errmess
});

export const addJobTitles = (jobTitles) => ({
    type: ActionTypes.GET_JOB_TITLES,
    payload: jobTitles
});

这是来自API的响应:

    "jobTitles": Object {
      "results": Array [
        "Engineer",
        "Software",
        "Software Architect",
        "Software Consultant",
        "Solution Architect",
        "System Architect"
      ]
  }

我希望HomeComponent.js中print()函数的console.log()语句能够打印来自API的JSON响应,但是它将返回“ undefined”。有什么想法吗?

任何帮助都会得到极大的帮助!

2 个答案:

答案 0 :(得分:0)

您应该使用this.props.jobTitles

mapStateToProps将数据从redux状态放到组件的props中。 this.state仅保留组件的本地状态。因此,在这种情况下,jobInputValueaddressInputValue。 mapStateToProps和mapDispatchToProps中的所有内容都将在道具中结束。 (如函数名称所示)

答案 1 :(得分:0)

在您的代码中:

this.state = { 
            jobInputValue: '',
            addressInputValue: ''
         };

您尝试打印的内容:

this.state.jobTitles

当然,它是未定义的!记录this.props.jobTitles或设置状态jobTitles以打印您想要的内容。