子コンポーネントにあるボタンを押すと、あらかじめ用意したテキストをStateに保存し、子コンポーネントの<Text>
内に表示される処理を行いたいです。
dispatch
からStore生成、mapStateToProps
での受け取りまでは正常に処理されているのですが、受け取った値の表示で以下のエラーになります。
Invariant Violation: Objects are not valid as a React child (found: object with keys {textStore}). If you meant to render a collection of children, use an array instead.
どのように修正すれば良いかがわかりません。
解決策を教えていただけると幸いです。
ソースコード
子コンポーネント
プロジェクト名/com.js
jsp
1import React, {Component} from 'react'; 2import {Text, View, Button, TextInput} from 'react-native'; 3import {connect, Provider} from "react-redux"; 4import App, {getData} from "../App" 5 6class Com extends Component { 7 constructor(props) { 8 super(props) 9 } 10 11 render(){ 12 return( 13 <View> 14 <Button 15 title="テキストを更新" 16 onPress={() => {this.props.updateText()}} 17 /> 18 <Text>{this.props.store.textStore}</Text> 19 </View> 20 ) 21 } 22} 23 24const mapStateToProps = (store, ownProps) => { 25 return { 26 store 27 } 28} 29 30const mapDispatchProps = (dispatch) => { 31 return { 32 updateText: () => { 33 dispatch({type: 'UPDATE_DATA', textStore: '更新されたテキスト'}) 34 } 35 } 36} 37 38export default connect(mapStateToProps, mapDispatchProps)(Com)
mapStateToProps
では、{textStore: "更新されたテキスト"}
でreturnしています。
親コンポーネント
プロジェクト名/App.js
jsp
1import React, {Component} from 'react'; 2import {Platform, StyleSheet, Text, View, Button, FlatList, TextInput} from 'react-native'; 3import { connect, Provider } from 'react-redux' 4import { createStore } from 'redux' 5 6import Com from './components/com' 7import reducer from './reducer/index' 8 9const store = createStore(reducer) 10 11type Props = {}; 12export default class App extends Component<Props> { 13 render() { 14 return ( 15 <View> 16 <Com store={store} /> 17 </View> 18 ); 19 } 20}
Reducer
/reducer/index.js
jsp
1export default reducer = (state = initialStore, action) => { 2 switch (action.type) { 3 case 'UPDATE_DATA': 4 return { textStore: action.textStore } 5 6 default: 7 return state.textStore 8 } 9}
回答1件
あなたの回答
tips
プレビュー