尝试使用this.props.dispatch并返回不是函数

时间:2018-04-21 08:31:05

标签: javascript reactjs react-native

我正在尝试从数据库中删除某个项目但是当我访问该功能时会说_this.props.dispatch is not a function. (In '_this.props.dispatch((0, _actions.deleteJob)(_this.props.id))', '_this.props.dispatch' is undefined)

这是我的代码,我在调用删除项目的函数。函数onDelete()我在用户交互后调用它。

class JobItem extends Component {
  constructor(props) {
    super(props)
    this.state = {
      activeRowKey: null,
      deleting: false
    };
  }
  onDelete = () =>   {
    this.setState({deleting: true});
    this.props.dispatch(deleteJob(this.props.id)); // HERE is the error
  }
  render() {
    const swipeSettings = {
      autoClose: true,
      onClose: (secId, rowId, direction) => {
        this.setState({ activeRowKey: null });
      },
      onOpen: (secId, rowId, direction) => {
        this.setState({ activeRowKey: this.props.id });
      },
      right: [
        { 
          onPress: () => {
            const deletingRow = this.state.activeRowKey;
            Alert.alert(
              'Alert',
              'Are you sure you want to delete?',
              [
                {text: 'No', onPress: () => console.log('Cancel Pressed'), style:'cancel'},
                {text: 'Yes', onPress: () => {
                  this.onDelete();
                  // Refresh Job List
                  this.props.parentFlatList.refreshJobList(deletingRow);
                }},
              ],
              { cancelable: true }
            )
          },
          text: 'Delete', type: 'delete'
        }
      ],
      rowId: this.props._id,
      sectionId: 1
    }

这是deleteJob()函数,它实际上是从DB

中删除它
export function deleteJob(job_id) {
  return function (dispatch) {
      return axios.delete(JOB_URL(user_id, job_id), {
        headers: { authorization: token }
      }).then((response) => {
        dispatch(removeJob(job_id));
      }).catch((err) => {
        dispatch(addAlert("Couldn't delete job."));
      });
  };
}

JobItem

var renderJobs = () => {
  return this.props.jobs.map((job) => {
    return (
      <JobItem 
        parentFlatList={this}
        key={job._id} 
        title={job.title} 
        shortDescription={job.shortDescription} 
        logo={job.avatar} 
        company={job.company} 
        id={job._id}/>
    )
  })
}
var mapStateToProps = (state) => {
  return {
    jobs: state.jobs
  }
}
module.exports = connect(mapStateToProps)(JobList);

我知道如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我认为您忘记将调度传递给JobItem

<JobItem 
    parentFlatList={this}
    key={job._id} 
    title={job.title} 
    shortDescription={job.shortDescription} 
    logo={job.avatar} 
    company={job.company} 
    id={job._id}
    dispatch={this.props.dispatch} /* <-- this one here */
/>

答案 1 :(得分:0)

解决问题的一种方法是将JobItem放在容器中。 像这样的东西

module.exports = connect(mapStateToProps,dispatch =&gt;({dispatch}))(JobItem);