this.props 'missing' method using conect f

2019-08-05 04:20发布

https://codesandbox.io/s/6l8zr5k94k

Why when I do this.props I see only object but not the function? but this.props.approveItem is there, this is so strange.

import React, { Component } from "react";
import { connect } from "react-redux";
import { approveItem } from "./actions";

@connect(state => state.items, { approveItem })
export default class Items extends Component {
  render() { 
    console.log('where is approveItem?', this.props);
    console.log('approveItem is here', this.props.approveItem);
    return (
      <div>
        <div>status: {this.props.item.status}</div>
        <button onClick={() => this.props.approveItem()}>Approve </button>
      </div>
    );
  }
}

2条回答
2楼-- · 2019-08-05 04:56

I'm not sure what exactly you are missing but running your code does print the props and shows the action as expected:

enter image description here

Edit
I think i know why you are not seeing the function when you log it.
You are looking at the console of the code sandbox application, which probably is doing a serialization of the props object.
The problem is that functions are not serialize-able.

From the docs:

Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string

You can run the code below to see how JSON.stringify for instance, is not serializing the function inside the object.

const obj = {
  someKey: 'some Value',
  someFunc: function() {}
};

console.log(JSON.stringify(obj));

FYI: You don't need to create an inline arrow function to pass it down to the onClick event, you can just pass the reference via the props.

So change this:

<button onClick={() => this.props.approveItem()}>Approve </button>

To this:

<button onClick={this.props.approveItem}>Approve </button>
查看更多
SAY GOODBYE
3楼-- · 2019-08-05 05:04

approveItem function is available in this.props

this.props.approveItem()

this.props is always an object, never be a function, Just think if we need to have multiple functions in props, we can have multiple function only if this.props is object. Not possible if this.props is itself as function.

Seeing methods in this.props object. Please look into console - https://codesandbox.io/s/xpy0lmolr4

查看更多
登录 后发表回答