Client(front단)

Ryu·2021년 12월 1일
0

Node_React

목록 보기
2/4
post-thumbnail

React

  • React를 사용하게 되면 javascript만을 가지고 개발하는 것보다 수월하게 개발을 진행할 수 있다.
  • 코드의 Component화를 통해 개발할 시 효율적이고 빠르게 개발 가능하다.
  • facebook에서 지원하는 오픈소스 라이브러리로 유지보수 혹은 트렌드에 뒤처질 가능성이 적다.

props and state

props

  • 컴포넌트 내부의 immutable Data
  • 부모 component가 자식 component에 값을 전달할 때 사용하는 것.(읽기전용)

state

  • state는 컴포넌트 자기 자신이 가지고 있는값
  • setState()함수를 통해 값을 변경해 줄수있다.
  • React에서 funtional 프로그래밍을 사용하며 useState()를 사용해 더 편하게 state값을 바꿀수 있게 되었다.
function Comments(props) {

    // Redux의 state에서 user정보를 가져오기
    const user = useSelector(state => state.user)
    const [Comment, setComment] = useState("")

    const handleChange = (e) => {
        setComment(e.currentTarget.value)
    }

    const onSubmit = (e) => {

        // 빈 comment를 Submit했을때 페이지가 refresh되는걸 막기위해
        e.preventDefault();

        const variables = {
            content: Comment,
            writer: user.userData._id,
            postId: props.postId
        }

Youtube_project에서 댓글파트에 대한 코드이다

  • useState를 사용하여 Comment에 대한 state값을 handleChange를 이용하여 바꿔 줬다.
  • 부모 Component인 Comment에서 props로 user의 정보를 같이 보내주며 자식 Component인 variables에서 postId:props.postId로 받아온 정보를사용한다

useEffect

  • React Component가 rendering 될때마다 특정작업을 실행할 수 있도록하는 Hook.
  • useEffect(function,deps)로 구성되며
  • function은 수행하고자 하는 작업
  • deps 는 배열 형태로 검사하고자 하는 특정 값 or 빈배열로 구성
function SideVideo() {

    const [SideVideos, setSideVideos] = useState([])

    useEffect(() => {
        axios.get('/api/video/getVideos')
            .then(response => {
                if (response.data.success) {
                    console.log(response.data.videos)
                    setSideVideos(response.data.videos)
                } else {
                    alert('Failed to get Videos')
                }
            })


    }, [])

Youtube_project에서 sideVideo component의 일부이다.

  • useEffect를 통해 랜더링 될때마다 video router에서 response.data.videos를 가져와 setSideVideos값을 바꿔준다.
  • 마지막 deps가 빈 배열이면 새로고침되고 처음 한번만 rendering되며 배열안에 만약 SideVideos등을 넣는다면 SideVideos의 값이 바뀔때마다 rendering이 된다.
profile
쓴다.노트.하는동안.공부

0개의 댓글