본문 바로가기
내마음대로만들어보자/React 프로젝트 만들기 이해

[React]스토어 주입하기

by 소농민! 2021. 11. 28.
728x90

1. 리덕스와 컴포넌트 연결하기

스토어를 주입할때는 Provider를 쓴다. (index.js 에 주입)

그 다음에는 App.js에서 원래 BrowserRouter와 Route를 써서 컴포넌트에 주입하던 history를

ConnectedRouter를 써서 리덕스랑 같은 history를 사용하도록 해줘야 히스토리를 공유할수있다.

 

1-1) index.js 에 스토어 주입하기

...
import store from "./redux/configureStore";
import { Provider } from "react-redux";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
...

1-2) App.js

...
import { ConnectedRouter } from "connected-react-router";
import { history } from "../redux/configureStore";
...
function App() {
  return (
    <React.Fragment>
      <Grid>
        <Header></Header>
        <ConnectedRouter history={history}>
          <Route path="/" exact component={PostList} />
          <Route path="/login" exact component={Login} />
          <Route path="/signup" exact component={Signup}/>
        </ConnectedRouter>
      </Grid>
    </React.Fragment>
  );
}
...

 

2. 로그인 액션 실행하기

리덕스 훅을 사용하여 간단하게 해볼 수 있다.

 

2-1) 로그인 페이지에서 리덕스 훅 사용하기

...
import {actionCreators as userActions} from "../redux/modules/user";
import { useDispatch } from "react-redux";

const Login = (props) => {
		const dispatch = useDispatch();
    const [id, setId] = React.useState('');
    const [pwd, setPwd] = React.useState('');

    const changeId = (e) => {
        setId(e.target.value);
    }

    const changePwd = (e) => {
        setPwd(e.target.value);
    }

    const login = () => {
				dispatch(userActions.login({user_name: "perl"}));
    }

    return (
        <React.Fragment>
            <Grid padding={16}>
                <Text type="heading">로그인 페이지</Text>
            </Grid>
            <Grid padding={16}>
                <Input value={id} onChange={changeId} placeholder="아이디를 입력하세요."/>
                <Input value={pwd} onChange={changePwd} type="password" placeholder="비밀번호를 입력하세요."/>
            </Grid>

            <Button __click={() => {login();}}>로그인</Button>
        </React.Fragment>
    )
}

export default Login;

2-2) 로그인하면 메인페이지로 이동하기

...
const loginAction = (user) => {
    return function (dispatch, getState, {history}) {
        dispatch(logIn(user));
        history.push('/');
    }
}

...

const actionCreators = {
  logIn,
  getUser,
  logOut,
  loginAction,
};

...

 

3. 헤더에서 스토어 데이터 보기

 

3-1) header.js 에서 리덕스 훅 사용하기 

...
import { useSelector, useDispatch } from "react-redux";
import { actionCreators as userActions } from "../redux/modules/user";
...
const Header = (props) => {
const dispatch = useDispatch();
const is_login = useSelector((state) => state.user.is_login);

    if(is_login){
        return (
          <React.Fragment>
            <Grid is_flex padding="4px 16px">
              <Grid>
                <Text margin="0px" size="24px" bold>
                  헬로
                </Text>
              </Grid>

              <Grid is_flex>
                <Button text="내정보"></Button>
                <Button text="알림"></Button>
                <Button text="로그아웃" _onClick={() => {dispatch(userActions.logOut({}));}}></Button>
              </Grid>
            </Grid>
          </React.Fragment>
        );
    }
    return (
        <React.Fragment>
            <Grid is_flex padding="4px 16px">
                <Grid>
                    <Text margin="0px" size="24px" bold>헬로</Text>
                </Grid>
                
                <Grid is_flex>
                    <Button text="로그인"></Button>
                    <Button text="회원가입"></Button>
                </Grid>
            </Grid>
        </React.Fragment>
    )
}

Header.defaultProps = {}

export default Header;