3

React, semantic-ui-react, redux-subspace를 사용하여 작은 앱을 제작하고 있습니다. 여러 테이블이 있는데 사용자가 셀 중 하나를 클릭하면 콘솔에서 값을 가져 오지만 결과는 클릭 할 때 정의되지 않습니다. 감속기를 재사용하려고합니다. 다른 인스턴스와 동일한 작업. 올바른 방향으로 안내하는 의견을 보내 주시면 감사하겠습니다.redux-subspace를 사용하여 동일한 작업으로 감속기를 재사용하는 방법

PartA.js

컴포넌트는 표를 렌더링하고 <SubspaceProvider> 래핑.

<Segment inverted color='black'> 
<h1>Age </h1> 
{ this.state.toggle ? 
<SubspaceProvider mapState={state => state.withSpouseAge} namespace="withSpouseAge"> 
    <TableForm 
     headers={spouse_ageHeaders} 
     rows={spouse_ageData} 
     namespace={'withSpouseAge'} 
    /> 
</SubspaceProvider> : 
<SubspaceProvider mapState={state => state.withoutSpouseAge} namespace="withoutSpouseAge"> 
    <TableForm 
     headers={withoutSpouse_ageHeader} 
     rows={withoutSpouse_ageData} 
     namespace={'withoutSpouseAge'} 
    /> 
</SubspaceProvider> } 

TableForm.js

데이터와이 구성 요소를 반환 테이블과 내가 온 클릭 메소드를 구현하고자하는 곳이다.

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import { Table } from 'semantic-ui-react'; 
import { select } from '../actions'; 

const shortid = require('shortid'); 

class TableForm extends Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
      activeIndex: 0, 
     } 
     this.handleOnClick = this.handleOnClick.bind(this); 
     this.isCellActive = this.isCellActive.bind(this); 
    }; 

    isCellActive(index) { 
     this.setState({ activeIndex: index }); 
    } 

    handleOnClick(index, point) { 
     this.isCellActive(index); 
     this.props.onSelect(point); 
    }; 

    tableForm = ({ headers, rows }) => { 
     const customRenderRow = ({ factor, point, point2 }, index) => ({ 
      key: shortid.generate(), 
      cells: [ 
       <Table.Cell content={factor || 'N/A'} />, 
       <Table.Cell 
        content={point} 
        active={index === this.state.activeIndex} 
        textAlign={'center'} 
        selectable 
        onClick={() => this.handleOnClick(index, point)} 
       />, 
       <Table.Cell 
        content={point2} 
        textAlign={'center'} 
        selectable 
       /> 
      ], 
     }); 
     return (
      <Table 
       size='large' 
       padded 
       striped 
       celled 
       verticalAlign={'middle'} 
       headerRow={this.props.headers} 
       renderBodyRow={customRenderRow} 
       tableData={this.props.rows} 
      /> 
     ) 
    }; 

    render() { 
     console.log(this.props.withSpouseAgePoint); 
     const { headers, rows } = this.props; 
     return (
      <div> 
       {this.tableForm(headers, rows)} 
      </div> 
     ); 
    } 
}; 

const mapDispatchToProps = (dispatch) => { 
    return { 
     onSelect: (point) => {dispatch(select(point))}, 
    } 
} 

const mapStateToProps = state => { 
    return { 
     withSpouseAgePoint: state.withSpouseAge, 
     withSpouseLoePoint: state.withSpouseLoe, 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(TableForm); 

액션

import { 
    SELECT, 
} from './types'; 

export const select = (points) => ({ 
    type: 'SELECT', 
    points, 
}); 

Reducer.js

import { SELECT } from '../actions/types'; 

const INITIAL_STATE = { 
    point: 0, 
}; 

const selectionReducer = (state = INITIAL_STATE, action) => { 
    switch (action.type) { 
     case 'SELECT': 
      return { ...state, point: state.point + action.points }; 
     default: 
      return state; 
    } 
}; 

export default selectionReducer; 

감속기

import { createStore, combineReducers } from 'redux'; 
import { subspace, namespaced } from 'redux-subspace'; 
import selectionReducer from './selectionReducer'; 
import toggleReducer from './toggleReducer'; 

const reducers = combineReducers({ 
    withSpouseAge: namespaced('withSpouseAge')(selectionReducer), 
    withSpouseLoe: namespaced('withSpouseLoe')(selectionReducer), 
    withSpouseOlp: namespaced('withSpouseOlp')(selectionReducer), 
    withSpouseOlp2: namespaced('withSpouseOlp2')(selectionReducer), 
    withSpouseExp: namespaced('withSpouseExp')(selectionReducer),  
    withoutSpouseAge: namespaced('withoutSpouseAge')(selectionReducer), 
    withoutSpouseLoe: namespaced('withoutSpouseLoe')(selectionReducer), 
    withoutSpouseOlp: namespaced('withoutSpouseOlp')(selectionReducer), 
    withoutSpouseOlp2: namespaced('withoutSpouseOlp2')(selectionReducer), 
    withoutSpouseExp: namespaced('withoutSpouseExp')(selectionReducer), 
    toggle: toggleReducer, 
}); 

업데이트하는 index.js

나는

const mapDispatchToProps = (dispatch) => { 
    return { 
     onSelect: (point) => {dispatch(select(point))}, 
    } 
} 

const mapStateToProps = state => { 
    return { 
     withSpouseAgePoint: state.withSpouseAge, 
     withSpouseLoePoint: state.withSpouseLoe, 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(TableForm); 

이 handleOnClick에 this.props.onSelect(point)을 구현 TableForm 구성 요소 아래에 추가. 그것은 여전히 ​​나에게 같은 결과를 보여줍니다 undefined. 상점 상태를 getState()으로 확인했습니다. consloe.log. 나는 redux-subspace 구현이 잘못되었다고 생각합니다. 전체 TableForm 구성 요소를 업로드하고 감속기를 업데이트했습니다. 제발 도와주세요!

업데이트는 2

나는 mapStateToProps 교체가 마법처럼 일했다. @ JustinTRoss 다시 한번 감사드립니다. 하지만 다른 문제가 있습니다. 셀을 클릭하면 모든 상태가 같은 값으로 나오게됩니다. console.log(props). 내 계획은 각각의 상태가 자신의 가치가 저장되어 있습니다.

const mapStateToProps = state => { 
    return { 
     withSpouseAgePoint: state, 
     withoutSpouseAge: state, 
    } 
} 

답변

2

이미 withSpouseAge에 구성 요소를 네임 스페이스와 SubspaceProvider에 state.withSpouseAge에 상태를 매핑했다. 따라서 state.withSpouseAge.withSpouseAge (undefined)와 동등한 함수를 호출합니다.

또 다른 잠재적 인 문제는 연결 전화와 관련된 서명입니다. 제공 한 스 니펫에서 '선택'의 가치를 확신 할 수있는 방법이 없습니다. 일반적으로 connect는 2 개의 함수 (mapStateToProps 및 mapDispatchToProps라고도 함)로 호출됩니다. 함수와 객체로 connect를 호출하고 있습니다. 당신이 정의하는 동안, 2 개 인자 (헤더 행)와 this.tableForm 전화하는거야 : 또한

import {connect} from 'react-redux' 

const TodoItem = ({todo, destroyTodo}) => { 
    return (
    <div> 
     {todo.text} 
     <span onClick={destroyTodo}> x </span> 
    </div> 
) 
} 

const mapStateToProps = state => { 
    return { 
    todo : state.todos[0] 
    } 
} 

const mapDispatchToProps = dispatch => { 
    return { 
    destroyTodo :() => dispatch({ 
     type : 'DESTROY_TODO' 
    }) 
    } 
} 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(TodoItem) 

다른 한 문제는 아직 당신에 영향을 미치는 것은 아니지만, 거기에, 다음은 http://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/#connect에서 예입니다 .tableForm 함수는 단일 인수를 사용하여 '헤더'및 '행'속성을 제거합니다.

+0

내가 해봤'const를 mapDispatchToProps = (파견) => { 반환 { onSelect를 : (점) => {파견 (선택 (점))} } }' – MachoBoy

+0

와'this.props를 추가합니다. onSelect' 클릭 방식 처리. 하지만 로그 콘솔을 사용하면 여전히 정의되지 않은 상태가됩니다. – MachoBoy

+0

@MachoBoy 문제 해결을 위해 mapStateToProps를 {withSpouseAgePoint : state} (으)로 변경하면 기록되는 내용은 무엇입니까? – JustinTRoss