2017-05-12 11 views
0

ここにはすばらしい回答がたくさんありますが、私はReactにはかなり新しいので、私の状況に適用するのが難しいです。コンポーネントがあり、そのコンポーネントにはWebサイトの訪問者に関するデータを保持する単一のレコードが渡されます。これらのフィールドの1つでは、外部ファイルに存在する関数を適用したいと考えています。以下のコードは未定義ReactJsコンポーネント内の小道具で関数を実行する

ActivityTable.jsのプロパティを読み取ることができませんChromeデベロッパーツールで実行時エラー 'prettyUserAgent' を与え

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などを使用することであらゆる種類のバリエーションを試しましたが、運が全くありません。

答えて

0

私はあなたのエラーコードの一部をUserAgentのようにデフォルト値を提供しているとして、この

StringManipulation.prettyUserAgent(this.state.userAgent) 

そして、あなたの状態の一部できたように見える可能性があり、この方法は仕事やないかどうかわからないが、ここで試していますこのように見える

var userAgentValue = this.props.activity.userAgent != undefined ? this.props.activity.userAgent : '' 
this.state = { userAgent: userAgentValue } 

したがって、activity.userAgentが定義されていない場合でも、文字列 ''値を取得します。

私はそれを実行してチェックすることはできませんが、私には論理的な解決策のようですが、間違った方向に考えていれば修正してください。

2

正しくインポートしませんでした。あなたは、その後、コードが

div className="small text-muted">{ prettyUserAgent(this.props.activity.userAgent) }</div> 
に変更する必要があります ActivityTable.js

import { prettyUserAgent } from '../../helpers/stringManipulation'; 

でこれを使用する必要があります

関連する問題