2017-04-04 62 views
1

这是我的组件无法读取的未定义的属性“toObject”当试图调用FUNC财产

class MyComponent extends Component { 
    render() { 
    const { action } = this.props; 
    action(); 
    return (<div>Done!</div>); 
    } 

MyComponent.propTypes = { 
    action: PropTypes.func.isRequired 
} 

这里是一个容器的相关代码:

doSomething() { 
    ... 
    } 
    render() { 
     return (
     <MyComponent 
     action={doSomething} 
     /> 
    ) 
    } 

当我打开这段代码在浏览器中,我得到了这个错误信息:

Uncaught TypeError: Cannot read property 'toObject' of undefined 

业务逻辑应该活在容器中,所以我不想警察y并将action的代码粘贴到MyComponent中。

所以我的问题是:如何在render方法中直接调用通过属性传入的函数?

+1

PLS显示action'的'代码。错误似乎发生在'action'内,这意味着'action'被调用。 – Panther

+0

@Ved如何操作this.props,他使用的是{action} = this.props',这就是所谓的'destructuring',该语法是正确的。 –

+0

@Panther你是对的。这个异常是在'action'函数内引发的。直到我将一个调试器语句放入函数中,它才从栈跟踪中显而易见。请让你的评论成为答案,我会接受。 –

回答

1

我认为,问题是在这个地方:

doSomething() { 
    ... 
} 

render() { 
    return (
    <MyComponent 
     action={doSomething} //here 
    /> 
    ) 
} 

它应该是:

doSomething() { 
    ... 
} 

render() { 
    return (
     <MyComponent 
     action={this.doSomething} 
     /> 
    ) 
} 

您需要使用this.doSomething,而不是doSomething

检查工作示例:

class App extends React.Component{ 
 

 
    constructor(){ 
 
     super(); 
 
    } 
 
    
 
    doSomething(){ 
 
     console.log('called'); 
 
    } 
 
    
 
    render(){ 
 
     return(
 
      <div> 
 
      Hello 
 
      <Child action={this.doSomething}/> 
 
      </div> 
 
     ) 
 
    } 
 
} 
 

 
var Child = (props) => { 
 
    const {action} = props 
 
    action(); 
 
    return(
 
    <div>Child</div> 
 
    ) 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'/>

相关问题