this.props'missing'方法,使用来自react-redux的conect
https://codesandbox.io/s/6l8zr5k94k
为什么当我执行此操作时,道具只看到对象,而看不到函数?但是this.props.approveItem在那里,真是太奇怪了.
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>
);
}
}
我不确定您到底缺少什么,但是运行代码确实会打印props
并按预期显示操作:
I'm not sure what exactly you are missing but running your code does print the props
and shows the action as expected:
修改
我想我知道为什么您在登录时看不到该功能.
您正在查看代码沙箱应用程序的console
,它可能正在对props
对象进行序列化.
问题是功能不可序列化.
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.
从文档中:
函数不是有效的JSON数据类型,因此它们将不起作用. 但是,如果先转换为字符串,则可以显示它们
Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string
您可以运行下面的代码,例如查看JSON.stringify
如何不序列化对象内部的函数.
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));
仅供参考:您无需创建内联箭头函数即可将其传递给onClick
事件,只需通过props
传递引用即可.
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
.
所以改变这个:
<button onClick={() => this.props.approveItem()}>Approve </button>
对此:
<button onClick={this.props.approveItem}>Approve </button>