如何直接调用道具?

问题描述:

我tryng调用道具功能直接this.props.setAuth();,但它似乎没有工作:/如何直接调用道具?

TypeError: Cannot read property 'props' of undefined

你如何去直接子组件调用函数的父母?

我想在没有任何事件处理程序的情况下更改父母状态,例如onClick={this.props.setAuth}。我想在异步函数中做到这一点,所以是的。

任何替代方法都会有所帮助。感谢:C

编辑:额外的代码:

class LoginPage extends Component { 
    constructor(props){ 
    super(props) 
    this.state = {auth: false} 
    this.setAuth = this.setAuth.bind(this) 
    } 

    setAuth() { 
    this.setState({auth: true}) 
    } 
<App setAuth={this.setAuth}/> 
下面

App组件,这是我想打电话给道具功能

onSignIn(googleUser) { 

(无用代码)的部分代码 - onSignIn位于App组件内

 axios.post('http://localhost:3000/auth', { 
     userId: id, 
     name: name, 
     email: email 
     }) 
     .then(function (response) { 
     this.props.setAuth(); 

     }) 
     .catch(function (error) { 
      console.log(error); 
     }); 


     }.bind(this)); 
+0

肯定有方法可以做到你在说什么。你可以发布一些代码,以便我们看看你是如何实现它的? – Emersonct

+0

添加一些代码以提供更多帮助 – Crysfel

+1

另外,从您收到的错误中,似乎'this'没有在您要调用this.props的作用域中定义。你使用的是一个函数类型的子组件(即不是一个类)? – Emersonct

这里举一些例子:

我的索引文件有这个组件和这个功能: 组件将作为道具接收一个回调函数。

<ArtistsSearchList 
    onArtistSelect={ 
     current_artist =>this.setArtist(current_artist) 
    } 
    key={this.state.term} 
    access_token=access_token} 
    term={this.state.term} /> 

setArtist(current_artist){ 
     this.setState({ 
      current_artist, 
      artist_image_url: current_artist.images[0].url 
     }); 
     var spotifyApi = new SpotifyWebApi(); 
     spotifyApi.setAccessToken(access_token); 
     spotifyApi.getArtistAlbums(current_artist.id, {album_type: 'album', limit: 10, market: 'BR'}, (err, data) => { 
     if(err){ 
      console.log(err); 
      // window.location.replace(api_url); 
     } 
     console.log(access_token); 
     console.log("Data: ", data); 
     console.log("State current artist: ", this.state.current_artist); 
     this.setState({ 
      albums: data.items, 
      selected_album_id: data.items[0].id 
     }); 
    }); 
} 

在ArtistsSearchList组件文件,我有这样的: 我会再次通过道具组件ArtistsSearchListItem

<ArtistsSearchListItem 
       key={artist.id} 
       current_artist={artist} 
       onArtistSelect={this.props.onArtistSelect} 
       artist_image_url={artist.images[0].url} /> 

在ArtistsSearchListItem文件的方法,我会finnaly通过所有这些方式作为道具传递的方法调用:

const ArtistSearchListItem = (props) => { 
    const artist_name = props.current_artist.name; 
    const artist_image_url = props.artist_image_url; 
    return(
     <li onClick={() => props.onArtistSelect(props.current_artist)} className="artist-search-list-item"> 
      <h3>{artist_name}</h3> 
      <img alt="Foto do artista" className="img-responsive img-thumbnail" src={artist_image_url}/> 
     </li> 
    ); 
} 

我的回购: https://github.com/igorPhelype/Spotigorfy

webapp的工作: https://igorphelype.github.io/Spotigorfy/

+0

这是一个很好的例子,谢谢你与我分享这个:) –

+0

竖起大拇指如果你喜欢它:) –

+0

只有当它解决了你的问题 –