2017-01-30 42 views
0

我一直在這個問題上停留了大約一個星期。我正在嘗試製作一個簡單的Pokedex(當然是原創151),右邊是一個口袋妖怪列表,右邊是一個.json文件(從一個api拷貝過來),然後點擊左邊填充該口袋妖怪的詳細信息取回。onClick調用獲取函數時的ReactJS組件生命週期。點擊狀態對象消失

我有我的狀態一個空的對象,我想從獲取數據來填充致電:

this.state = { 
    pokemonList: local, 
    pokemon: {}, 
    name: '', 
    url: '', 
} 

的名稱和網址數值直接從onClick事件填充,然後將URL值用於提取。

fetchSinglePokemon(event) { 
     fetch(event.target.value) 
      .then(response => response.json()) 
      .then(pokemon => console.log(pokemon)) 
      .then(pokemon => this.setState({ pokemon: pokemon })); 
    } 
setSinglePokemon(pokemon) { 
     this.setState({ pokemon: pokemon }); 
    }  

這兩種方法運行後,我可以看到所有我想在控制檯中的數據JSON對象,但在陣營DevTools,在國家空的對象,我要重寫,從取出完全的狀態對象。點擊另一個選項將更新名稱和URL,但小精靈對象將永遠不會回來。

寵物小精靈是另一個沒有任何狀態的組件,並且收集所有的道具。即使它只是顯示信息,那麼這個組件是否也需要成爲一個類?

我已閱讀有關組件生命週期文檔中的所有內容,並且找不到與我的需求相關的任何內容。

我的思考過程是在componentMount上設置狀態,並使用onClick事件控制狀態的componentWillUpdate。

我一直在努力學習React與反應電子書和Wes Bos React課程的道路,但改變了我想要的應用程序,以便我實際學習它如何工作,而不是僅僅複製某些內容,但這兩個來源都與我前往的地方不同。

Here's a link to my Repo

預先感謝您,並請移動這個反應的學習子,我錯過了。

回答

1

有一點需要警惕的:

fetchSinglePokemon(event) { 
     fetch(event.target.value) 
      .then(response => response.json()) 
      .then(pokemon => console.log(pokemon)) <- this guy right here. 
      .then(pokemon => this.setState({ pokemon: pokemon })); 
    } 

標記在上面例子中的線將導致以下thenable具有pokemon設置爲未定義。 response.json()解析爲json對象,console.log將導致thenable使用undefined進行解析。

,可能是更好的措辭 - 但這裏有一個更直觀的方式:

fetchSinglePokemon(event) { 
     fetch(event.target.value) 
      .then(response => response.json()) 
      //pokemon in the line below will be the json object 
      .then(pokemon => console.log(pokemon)) 
      //pokemon in the line below will be undefined because you didn't return anything from the above block. 
      .then(pokemon => this.setState({ pokemon: pokemon })); //this will look like: {pokemon:undefined} 
    } 

試試這個:

fetchSinglePokemon(event) { 
     fetch(event.target.value) 
      .then(response => response.json()) 
      .then(pokemon => { 
       console.log(pokemon); 
       return pokemon; 
      }) 
      .then(pokemon => this.setState({ pokemon: pokemon })); 
    } 
+1

你先生是當場上!我永遠不會認爲這會是一個問題。在我的情況下,應該在哪裏使用組件生命週期方法。有相當多的加載時間,大約一秒鐘的時間來完成抓取,所以我應該使用其中一種方法來指示加載或停止另一次抓取? – lockykeaney

+0

我認爲規範的方法是使用'componentDidMount'方法。但我必須承認 - 根據我的經驗 - 你永遠不會那麼做。 React is wayyyyyyy更好地與你一起工作沒有組件大驚小怪的改變狀態等。讓你的商店處理它,讓組件引發事件。 –