前提・実現したいこと
react-reduxでstateを更新した時に再レンダリングして画面に描画したいです。
該当のソースコード
index.js
javascript
1import React, { Component } from "react"; 2import { connect } from "react-redux"; 3import * as actions from "../actions"; 4 5class App extends Component { 6 renderResult() { 7 console.log(this.props.result); 8 if (!this.props.result) { 9 return <div>No Result!!!</div>; 10 } else { 11 return <div>{this.props.result}</div>; 12 } 13 } 14 15 render() { 16 return ( 17 <div> 18 <button onClick={this.props.getGenders}>get genders</button> 19 {this.renderResult()} 20 </div> 21 ); 22 } 23} 24 25const mapStateToProps = state => { 26 return { result: state.result }; 27}; 28 29export default connect( 30 mapStateToProps, 31 actions 32)(App); 33
action
Javascript
1import axios from "axios"; 2import { GET_GENDERS } from "./types"; 3 4export const getGenders = () => async dispatch => { 5 try { 6 const response = await axios.get("http://localhost:3090/gender"); 7 dispatch({ type: GET_GENDERS, payload: response.data }); 8 } catch (e) { 9 console.log("error"); 10 } 11};
reducer
javascript
1import { GET_GENDERS } from "../actions/types"; 2 3const INITIAL_STATE = { 4 result: "" 5}; 6 7export default function(state = INITIAL_STATE, action) { 8 switch (action.type) { 9 case GET_GENDERS: 10 return { ...state, result: action.payload }; 11 default: 12 return state; 13 } 14}
試したこと
button(getGenders)をクリックした時にAction内でaxiosのリクエストが発行され、reducers側で正しくstateが更新されることは確認できています。(Reduxのstate上はgenders > resultにxmlの結果が格納されています)
上記JavaScriptのthis.renderResult()の箇所でうまく再レンダリングさせて画面上に表示させたいのですが、どのように実装すれば良いでしょうか。
アドバイスいただけると幸いです。
アクションクリエータとリデューサーのソースコードも質問に追記頂けると、より多くの回答が得られるかもしれません。
追記致しました。ありがとうございます!
追記ありがとうございます。どこがおかしいのか見始めていますが、あともう2点だけ確認させてください。(1) たぶん合ってると思いますが念のための確認です。Redux と非同期処理の連携のために、 redux-thunk をお使いでしょうか? (2) ご質問の中に、「 resultにxmlの結果が格納されています」とあったので、 http://localhost:3090/gender によってXMLが返され、やりたいことは、このレスポンスのXML全体を文字列として redux state の genders.result に入れ、これを画面に <div>で囲って表示したい、ということでよいでしょうか?
(1) redux-thunkを利用しています!
```index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import reduxThunk from "redux-thunk";
import reducers from "./reducers";
import App from "./components/App";
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(reduxThunk))
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querySelector("#root")
);
```
(2) はい、そうです!正確にはそのxmlの中身を加工して画面に出力、、ということを後ほど実施したいのですが、直近の目標として全て出力することをしたいです!
ご返信ありがとうございます。回答しました。
回答2件
あなたの回答
tips
プレビュー