这里有很多关于 SO 的优秀答案,但我很难将它们应用到我的环境中,因为我对 React 还很陌生。我有一个组件,并向该组件传递一条保存有关网站访问者数据的记录。在这些字段之一上,我想应用驻留在外部文件中的函数。下面的代码在 Chrome 开发者工具中给出了运行时错误无法读取未定义的属性“prettyUserAgent”
ActivityTable.js
import React, { Component } from 'react';
import { StringManipulation } from '../../helpers/stringManipulation';
export class ActivityTableItem extends Component {
constructor() {
super();
this.state = { userAgent: '' }
}
render() {
return (
<tr onClick={(e) => { e.preventDefault(); }}>
<td>
<div>{ this.props.activity.websiteUri }</div>
</td>
<td>
<div>{ this.props.activity.ipAddress }</div>
</td>
<td>
<div className="small text-muted">{ StringManipulation.prettyUserAgent(this.props.activity.userAgent) }</div>
</td>
<td className="text-center">
<img src={'/img/flags/USA.png'} alt="USA" style={{height: 24 + 'px'}}/>
</td>
<td>
<div>{ this.props.activity.createdAt }</div>
</td>
</tr>
)
}
}
StringManipulation.js
import UAParser from 'ua-parser-js';
// Create a pretty string to display main details from a user agent
export const prettyUserAgent = (str) => {
const parser = new UAParser();
const result = parser.setUA(str).getResult();
const browser = result.browser;
return result.browser;
};
我明白为什么会发生这个错误,该函数是在数据存在之前调用的,但不知道如何修复它。我尝试了使用 componentDidMount 等的各种变体,但没有任何运气。
最佳答案
您没有正确导入。您应该在 ActivityTable.js
import { prettyUserAgent } from '../../helpers/stringManipulation';
那么代码应该改为
div className="small text-muted">{ prettyUserAgent(this.props.activity.userAgent) }</div>
关于javascript - 在 ReactJs 组件中的 props 上运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43928212/