2017-05-31 61 views
0

我試圖在數組中創建布爾過濾器。將Button中的值傳遞給數組中的setState

  1. 如果一個按鈕是「活動」(True),它應該添加按鈕名稱到數組(「選擇」)。

  2. 如果按鈕是「非活動」(false),它應該將其從數組中移除。

但是,只有一些值以set狀態結束。我把它放在一個codepen: https://codesandbox.io/s/wpxD35Oog

import React from 'react'; 
import { render } from 'react-dom'; 
import { x } from './data.js'; 

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     movies: x.movies, 
    }; 
    } 
    render() { 
    const uniqueGenres = [] 
     .concat(
     ...this.state.movies.map(movies => 
      movies.genres.map(genres => genres.name), 
     ), 
    ) 
     .filter((genre, i, _) => _.indexOf(genre) === i); 
    return (
     <div> 
     <div> 
      {uniqueGenres.map(e => <Filter1 key={e} result={e} />)} 
      <br /> 
     </div> 
     </div> 
    ); 
    } 
} 

class Filter1 extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     active: true, 
     selected: '', 
    }; 
    } 
    handleActive = e => { 
//  this.setState(previousState => ({ 
//  selected: [...previousState.selected, e.target.value] 
// })); 
    console.log('pre-setState', e.target.value); 
    const active = !this.state.active; 
    const selected = e.target.value; 
    this.setState({ 
     active: active, 
     selected: selected, 
    }); 
    console.log('status', this.state.active, this.state.selected); 
    }; 
    render() { 
    return (
     <span> 
     <button onClick={this.handleActive} value={this.props.result}> 
     {this.props.result} {}<b> 
      {this.state.active ? 'Active' : 'Inactive'} 
     </b> 

     </button> 
     </span> 
    ); 
    } 
} 

回答

1

理想情況下,你願意讓(在這種情況下,應用)父組件照顧管理活動流派。我重寫了部分代碼來演示它:https://codesandbox.io/s/JZWp1RQED

+0

幾乎在那裏 - 謝謝!爲了傳遞值,我真的只想在'selectedMap'中的值,即console.log(this.state.selectedMap)應該返回'{SuperDooper,Movie}'而不是'{SuperDooper:true,Movie:true }' – Ycon