react + redux toolkit にて入力欄の追加ボタンを実装しようとしているのですが
ローカル関数での配列操作をうまくstateに反映できていないようで
ボタンを押しても入力欄がうまく追加されません。。。
以下のようなコードなのですが
"+" ボタンを押しても何も反応せずでして・・・
(consoleを見る限り、ローカル関数内の配列は無事に追加できているようなのですが、、)
原因と修正方法お分かりの方いらっしゃいましたら
ご教授お願いします。。。
index.js
1import React from "react"; 2import './index.css'; 3import ReactDOM from "react-dom"; 4import App from "./App"; 5import { Provider } from "react-redux"; 6//import { setupStore } from "./store"; 7import * as serviceWorker from './serviceWorker'; 8import { store } from './store'; 9 10//const store = setupStore(); 11 12ReactDOM.render( 13 <Provider store={store}> 14 <App /> 15 </Provider>, 16 document.getElementById("root") 17); 18 19// If you want your app to work offline and load faster, you can change 20// unregister() to register() below. Note this comes with some pitfalls. 21// Learn more about service workers: https://bit.ly/CRA-PWA 22serviceWorker.unregister();
import React from "react" import { useDispatch, useSelector } from "react-redux" import { useForm } from 'react-hook-form' import { setAddresses } from './rootSlice' import './common.css' const App = () => { const dispatch = useDispatch(); const Addresses = useSelector(state => state.Addresses) const { register, handleSubmit } = useForm(); const addresses = ["address0"] const onSubmit = (data) => { dispatch(setAddresses(data.addresses)) } const addAddress = () => { addresses.push(`address${addresses.length}`) console.log("addresses: ", addresses) } return ( <form onSubmit={handleSubmit(onSubmit)}> <div className="div-block"> {Addresses.map((address, index) => { return ( <> <label>Address {index}</label> <input name={`addresses[${index}]`} ref={register} /> </> ) })} <button type="button" onClick={addAddress}>+</button> <button type="submit" className="btn-square-shadow">Apply !</button> </div> <div> <hr></hr> {Addresses.map((address, index) => { return ( <> <div>Address {index}: {address}</div> </> ) })} </div> </form> ); }; export default App;
import { createSlice } from '@reduxjs/toolkit' const rootSlice = createSlice({ name: "address", initialState: { Name: "XXXX", Addresses: ["hoge-1-1-1"] }, reducers: { setName: (state, action) => { state.Name = action.payload }, setAddresses: (state, action) => { state.Addresses = action.payload }, } }) export const reducer = rootSlice.reducer; export const { setName, setAddresses, addAddresses } = rootSlice.actions
import { configureStore } from '@reduxjs/toolkit' import { reducer } from './rootSlice' export const store = configureStore({ reducer })
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。