2017-06-23 12 views
1

私はReduxを学んでいます。同じコンテナで、mapStateToPropsとmapDispatchToPropsを使用したいと思います。私は別の容器にこれらを分離した場合、私は、これはエラーなしで仕事を得ることができますが、私は両方とも同じ容器に入れしようとした場合、何らかの理由でそれが次のエラーを与える:Reduxでエラーが発生しました:「同じキーを持つ2人の子供がいる」このエラーを解決するには?

"bundle.js:2296 Warning: flattenChildren(...): 
Encountered two children with the same key, `.$1`. 
Child keys must be unique; when two children share a key, 
only the first child will be used." 

はそれがにOKですmapStateToPropsとmapDispatchToPropsを同じコンテナで同時に使用しますか?すべて動作しますが、私はまだコンソール上でエラーが発生し、正確に何を意味するのか把握したいと思います。

ここは私のコンテナです。 (:fetchAstronautとshowNotification私は行動する必要があります):もちろん

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { bindActionCreators } from 'redux'; 
import { fetchAstronaut } from '../actions/index'; 
import { showNotification } from '../actions/index'; 

class SearchBar extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      text: '' 
     } 
    } 
    displaySearch(e) { 
     this.setState({ text: e.target.value }) 
    } 

    formSubmit(e) { 
     e.preventDefault(); 
     this.props.fetchAstronaut(this.state.text); 
     this.setState({ text: ''}); 
     this.props.showNotification(); 
    } 

    render() { 
     return (
      <div> 
       <div> 
        <form onSubmit={(e) => this.formSubmit(e)}> 
         <input 
          value = { this.state.text } 
          onChange={(e) => this.displaySearch(e) } 
         /> 
         <button type="submit">Search</button> 
        </form> 
       </div> 
       <div> 
        <h1>{this.props.notification}</h1> 
       </div> 
      </div> 
     ); 
    } 
} 

function mapStateToProps({ notification }) { 
    return { notification }; 
} 

function mapDispatchToProps(dispatch) { 
    return bindActionCreators({ fetchAstronaut, showNotification }, dispatch); 
} 

export default connect(mapStateToProps, mapDispatchToProps)(SearchBar); 

答えて

2

あなたが見ているされているのと同じ容器に同時にmapStateToPropsとmapDispatchToPropsを使用するのは間違いなく大丈夫です、エラー他の場所です。

コンポーネントの反応リストを渡すときはいつでも、それらのコンポーネントのそれぞれに一意のIDを割り当てます。たとえば、コードを持っている場合:

const Comp = (props) => { 
const l =[1,2,3,4] 
const lc = l.map((ix) => (<p>{ix}</p>)) 
return (
    <div>{lc}</div> 
) 
} 

あなたに似たようなエラーが発生します。これを修正するには、

const lc = l.map((ix) => (<p key={ix}>{ix}</p>)) 

に変更する必要があります。これにより、各段落に固有のキーが割り当てられます。

1

それは本当にお勧めです実際には、mapStateToPropsmapDispatchToPropsを使用しても大丈夫です。

警告に関しては、react-JSXの警告です。同じレベルに2つのdivをキーなしで含めています。彼らは 'キー'パラメータを持っていなければならず、それらは異なっていなければなりません。

render() { 
    return (
     <div> 
      <div key='1'> 
       <form onSubmit={(e) => this.formSubmit(e)}> 
        <input 
         value = { this.state.text } 
         onChange={(e) => this.displaySearch(e) } 
        /> 
        <button type="submit">Search</button> 
       </form> 
      </div> 
      <div key='2'> 
       <h1>{this.props.notification}</h1> 
      </div> 
     </div> 
    ); 
} 
関連する問題