【问题标题】:React - props is not definedReact - 未定义道具
【发布时间】:2018-04-18 07:15:00
【问题描述】:

我有两个组件。

  1. MypropDestructuring.jsx(主要组件)
  2. MypropDestructuringMessage.jsx(用于道具解构)(我是 React 中解构概念的新手)

我认为我在 (MypropDestructuringMessage.jsx) 道具解构中做错了。

在控制台日志中我收到以下错误-

Uncaught ReferenceError: props is not defined at MypropDestructuringMessage.render (index.js:33930)

代码:

MypropDestructuring.jsx

// Let's import react
import React from "react";

// Import custom component
import MypropDestructuringMessage from "./MypropDestructuringMessage.jsx";


// Let's create component [[ MypropDestructuring ]]
class MypropDestructuring extends React.Component{

    // Let's create custom method
    _myProfile() {

        const myProfileData = [
            {
                id : 1,
                name : "Neon",
                age : 25,
                location : "UK",
                skill : "UI Dev"
            }
        ];

        // return
        return myProfileData.map( (profileArrg) => {

                return( 
                    <MypropDestructuringMessage key={profileArrg.id} name={profileArrg.name} age={profileArrg.age} location={profileArrg.location} skill={profileArrg.skill} /> 
                );
            }
        );

    }

    render(){

        const showProfile = this._myProfile();
        return(
            <section>

                <p>&nbsp;</p>
                <h6> Prop Desturcturing </h6>
                <hr />

                <div>
                    {showProfile}
                </div>

            </section>
        );
    }
}


// Let's render ReactDOM
export default MypropDestructuring;

MypropDestructuringMessage.jsx

// Let's import react
    import React from "react";

    // Let's create component [[MypropDestructuringMessage]]
    class MypropDestructuringMessage extends React.Component{
        render(){


            // Props destructuring
            const {name, age, location, skill} = props;

            return(

                <section>

                    <div>
                        <ul className="list-group">
                            <li className="list-group-item"> {name} </li>   
                            <li className="list-group-item"> {age} </li>   
                            <li className="list-group-item"> {location} </li>   
                            <li className="list-group-item"> {skill} </li>    
                        </ul>
                    </div>

                </section>
            );
        }
    }

    // Let's pass data with [[ propTypes ]] - object
    MypropDestructuringMessage.propTypes = {
        name : React.PropTypes.string.isRequired,
        age : React.PropTypes.number.isRequired,
        location : React.PropTypes.string.isRequired,
        skill : React.PropTypes.string.isRequired
    }


    // Let's render ReactDOM
    export default MypropDestructuringMessage;

【问题讨论】:

  • 你应该这样做.props
  • profileArrg也未定义

标签: reactjs


【解决方案1】:

不仅使用props,还使用this.props

const {name, age, location, skill} = this.props;

这是Destructuring assignment上的文档

【讨论】:

  • 感谢 Vivek,我是了解解构的新手。你能分享一些关于解构的例子吗?
  • @Sandy,当然,更新了答案,请看一下。
  • @Sandy ,你可能也想读这个stackoverflow.com/questions/44734548/…
【解决方案2】:

道具绑定到组件的上下文 (this),它们不是全局的,这就是您收到错误的原因。使用this.props 而不是props,除非您需要在构造函数中处理它们,因为在构造函数中 this.props 仍然未定义。如果您需要在构造函数中使用道具,它们将作为参数发送:

constructor(props) {
    super(props);
    // this.props is not defined at this point, so you have to use props
    // do something with props here
}

您可以在 react in this article 中阅读更多关于 props 的信息,这对 React 新手或想要更新知识的人很有用,如果您有兴趣,请查看!

【讨论】:

    【解决方案3】:
    import React, { Component } from 'react'
    import ReactDOM from 'react-dom'
    import axios from 'axios'
    
    import PairsList from './PairsList.jsx'
    import RosterList from './RosterList.jsx'
    import NewPairsForm from './NewPairsForm.jsx'
    
    export default class App extends Component {
      constructor() {
        super()
        this.state = {
          rosterOrPairs: true,
          cohort: []
        }
        this.title = 'Pairs'
        this.onClickRoster = this.onClickRoster.bind(this)
        this.onClickPairs = this.onClickPairs.bind(this)
      }
    
      componentWillMount() {
        axios.get('/cohort')
          .then( (response) => {
            console.log('response.data is ', response.data)
            this.setState({ cohort: response.data })
          })
          .catch( (error) => console.log(error) )
      }
    
      onClickRoster() {
        this.setState({ rosterOrPairs: true })
      }
    
      onClickPairs() {
        this.setState({ rosterOrPairs: false })
      }
    
      render() {
        return(
          <div>
            <div className="title">{this.title}</div>
            <NewPairsForm cohort={this.state.cohort} />
            <div className="buttons-section">
              <button onClick={this.onClickRoster}>Roster</button>
              <button onClick={this.onClickPairs}>Pairs</button>
            </div>
            { this.state.rosterOrPairs ? <RosterList cohort={this.state.cohort} /> : <PairsList /> }
          </div>
        )
      }
    }
    
    ReactDOM.render(<App/>, document.getElementById('app'))
    

    【讨论】:

    • 请描述一下。
    • '( var searchYouTube = ({key, query, max = 5}, callback) => { $.get('googleapis.com/youtube/v3/search', { part: 'sn-p', key: key, q: query, maxResults: max, type: 'video', videoEmbeddable: 'true' }) .done(({items}) => { if (callback) { callback(items); } }) .fail( ({responseJSON}) => { responseJSON.error.errors.forEach((err) => console.error(err) ); }); }; window.searchYouTube = searchYouTube; ')
    • ReactDOM.render( , document.getElementById('app') );
    • this.state = { 视频:[], currentVideo: null }; handleVideoListEntryTitleClick(video) { this.setState({ currentVideo: video }); } render() { return (
    • handleInputChange(e) { this.props.handleSearchInputChange(e.target.value); this.setState({ value: e.target.value }); } render() { return (
      ); }
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签