代码之家  ›  专栏  ›  技术社区  ›  flo527

类型错误:componentdidmount内的defaultpieces不是函数

  •  0
  • flo527  · 技术社区  · 7 年前

    在我的possibleMatches组件内部,我从我的操作/索引文件导入了一些异步函数,当我在componentdidmount内部调用这些函数时,我得到的错误是:defaultPieces is not a function.

    下面是我的possibleMatches组件和actions/index.js文件的内容:

    为了简洁起见,我尽力添加了与主要问题相关的所有内容。

    possibleMatches.js.

    import connect from'react redux';
    从'../actions/index'导入排列件、默认件、设置评估件、获取对应件;
    
    建造师(道具){
    超级(道具);
    
    常量首字母={
    当前组件:whichpiece:whichtype:空,currentuppercomponent:空,currentlowercomponent:空,
    上部件:this.props.uppercomponents,
    低级组件:this.props.lowercomponents,
    upperComponentEnabled:错误,
    包含的较低组件:错误,
    获取:错误,
    正在提取:对
    }
    
    本州={
    …首字母
    }
    
    this.residinguppercomponent=createRef();
    this.residingLowerComponent=createRef();
    //如果上下组件的回调经过时间,则还需要基于this.props.setCurrentComponent的this.prop.setEvaluatedpiece
    this.setNewPiece=this.setNewPiece.bind(this);
    
    this.renderDecision=this.renderDecision.bind(this);
    }
    
    
    异步组件didmount()。{
    
    const store=this.context;
    让stateRef=store.getState();
    
    const defaultpieces,arrangepieces=this.props;
    
    尝试{
    const summon=()=>defaultPieces();
    排列件();
    等待召唤();
    }捕获(错误){
    投掷误差(误差);
    }
    
    console.log(“afewovmaovhie”)。
    this.setState(已获取:true,正在获取:false);
    }
    
    renderDecision()。{
    
    const currentcomponent、lowercomponentenabled、uppercomponentenabled、isfetching、isfetched=this.state;
    const建议底部、建议顶部、上部组件、下部组件=this.props;
    
    如果(正在获取){
    返回(<div classname='activityloader'>
    <activityindicator number=3 duration=200 activecolor=“fff”borderwidth=2 bordercolor=“50%”diameter=20/>
    </DIV>);
    }否则,如果(已获取){
    返回(
    
    <div classname=“possibleMatches_container”>
    <i classname='capturecourt'onclick=this.Snapshotmatch></i>
    <transitionGroup组件=可能的匹配项>
    ******uppercomponents.map((component)=>。{
    返回(<uppercomponent key=component.created_at id=component.id_
    switchcomponent=this.switchfocus_
    setCurrentPiece=this.setNewPiece_
    evaluatePiece=this.isopposite组件建议
    image=组件.image
    toggleTopence=()=>if(lowercomponentenabled==false)this.setState(lowercomponentenabled:true)else return;this.setState(currentLowercomponent:suggestedBottoms[0])
    IsLowerComponentEnabled=LowerComponentEnabled_
    ref=this.residinguppercomponent_
    classname=currentComponent.whichPiece.whichType=='匹配'?'可能的匹配“容器”:currentComponent.whichPiece.whichType=='底部'?'标准件“:‘标准件’/>
    )
    })
    }
    </TransitionGroup>
    <transitionGroup组件=可能的匹配项>
    lowercomponents.map((component)=>。{
    返回(<lowercomponent key=component.created_at id=component.id_
    setCurrentPiece=this.setNewPiece_
    evaluatePiece=this.isopposite组件建议
    image=组件.image
    toggleTopence=()=>if(upperComponentEnabled==false)this.setState(upperComponentEnabled:true)else return;this.setState(currentUpperComponent:SuggestedTops[0])
    switchcomponent=this.switchfocus_
    isuppercomponentEnabled=uppercomponentEnabled
    ref=this.residinglowercomponent
    classname=this.state.currentcomponent.whichPiece.whichType=='匹配'?'可能的匹配“容器”:this.state.currentcomponent.whichPiece.whichType=='底部'?'Standalonepice':'Standalonepice'/>)
    
    })
    }
    </TransitionGroup>
    </DIV>
    )
    }
    }
    
    呈现()。{
    
    
    返回(
    
    <DIV classname='GorClosingContainer'>
    <walker uppercomponent=this.state.currentcomponent.whichpiece.currentuppercomponent lowercomponent=this.state.currentcomponent.whichpiece.currentlowercomponent enableCapture=(snapshot)=>this.snapshotmatch=snapshot/>
    this.renderDecision()
    </DIV>
    ;
    }
    
    函数mapstatetoprops(state){
    施工上部构件、下部构件、预期构件、临时顶、临时底、临时底、临时底、临时底、临时底、临时底、建议底、建议底、建议底=State.possibleMatches;
    返回上部件、下部件、预期部件、外顶部、外底部、标准底部、标准底部、建议底部、建议顶部;
    }
    
    导出默认连接(mapstatetoprops,默认件,排列件,getcorrespondingpieces,setevaluatedpiece)(可能的匹配)
    

    在我的操作/index.js中

    export function defaultpieces()。{
    返回功能(调度){
    fetch(`$api_url/possible_matches/setup_possible_matches`,,{
    标题:{
    “accept”:“应用程序/json”,
    'content type':'application/json'
    }
    })。然后((res)=>res.json())
    。然后((json)=>。{
    console.log('默认项:',json);
    调度(getinitialpieces(json))
    })
    }
    }
    
    导出函数getInitialPieces(请求){
    返回{
    类型:首件
    有效载荷:请求
    }
    }
    

    Inside of possibleMatches Reducer:

    import initial_pieces,get_ancillary_pieces,organize_pieces,set_expected_pieces from'../actions/types';
    
    常量首字母={
    上部组件:[],
    低成分:【】,
    预期\件:空,
    额外费用:【】,
    外底:
    Standalonetops公司:【】,
    标准底部:
    建议操作:【】,
    建议底部:[]
    }
    
    导出默认函数(状态=初始状态,操作){
    
    
    开关(动作类型){
    箱首件:
    返回…状态,预期件:action.payload.expected件,
    附加装置:action.payload.extra-top,
    外底:action.payload.extra ou bottoms,
    standalone tops:action.payload.standalone_-top,
    StandaloneBottoms:action.payload.standaloneBottoms,
    建议的操作:action.payload.suggested\tops,
    建议的底部:行动。有效载荷。建议的底部
    箱获取辅助件:
    返回…状态,附加:action.payload.extra-tops,
    外底:action.payload.extra ou bottoms,
    standalone tops:action.payload.standalone_-top,
    StandaloneBottoms:action.payload.standaloneBottoms,
    建议的操作:action.payload.suggested\tops,
    建议的底部:行动。有效载荷。建议的底部
    案例整理:
    返回…状态,上部组件:action.payload.uppercomponents,
    低部件:action.payload.lowercomponents_
    包装箱:
    返回…状态,预期件:动作。有效载荷。预期
    违约:
    返回状态;
    
    }
    

    }

    因为defaultpieces对于possiblematches组件不是有效的函数,它会干扰来自mapstatetoprops函数(用*表示)的uppercomponents属性的解释。

    奇怪的是,json从arrangepieces和defaultpieces方法中注销到控制台:

    .

    以下是我的possibleMatches组件和actions/index.js文件的内容:

    为了简洁起见,我尽力添加了与主要问题相关的所有内容。

    可能的匹配.js

    import { connect } from 'react-redux';
    import {arrangePieces, defaultPieces, setEvaluatedPiece, getCorrespondingPieces} from '../actions/index';
    
          constructor(props){
            super(props);
    
            const initialState = {
                currentComponent: {whichPiece: {whichType: null, currentUpperComponent: null, currentLowerComponent: null}},
                UpperComponents: this.props.UpperComponents,
                LowerComponents: this.props.LowerComponents,
                UpperComponentEnabled: false,
                LowerComponentEnabled: false,
                isFetched: false,
                isFetching: true
            }
    
            this.state = {
               ...initialState
            }   
    
            this.residingUpperComponent = createRef();
            this.residingLowerComponent = createRef();
        //Also need to this.prop.setEvaluatedPiece based off of this.props.setCurrentComponent if callback from Lower or Upper Components elapses time
            this.setNewPiece = this.setNewPiece.bind(this);
    
            this.renderDecision = this.renderDecision.bind(this);
        }
    
    
        async componentDidMount(){
    
           const {store} = this.context;
           let stateRef = store.getState();
    
            const { defaultPieces, arrangePieces } = this.props;
    
           try {
               const summon = () => { defaultPieces();
                                      arrangePieces();}
               await summon();
            } catch(error){
               throw Error(error);
            }
    
            console.log("AFEWOVMAOVHIE")
            this.setState({isFetched: true, isFetching: false});
        }
    
        renderDecision(){
    
        const { currentComponent, LowerComponentEnabled, UpperComponentEnabled, isFetching, isFetched} = this.state;
        const { suggestedBottoms, suggestedTops, UpperComponents, LowerComponents } = this.props;
    
        if (isFetching){
             return (<div className='activityLoader'>
                        <ActivityIndicator number={3} duration={200} activeColor="#fff" borderWidth={2} borderColor="50%" diameter={20}/>
                     </div>);
        } else if (isFetched){
                return (
    
                    <div className = "PossibleMatches_Container">
                           <i className = 'captureOutfit' onClick = {this.snapshotMatch}></i> 
                           <TransitionGroup component = {PossibleMatches}>
                             ** ** ** {UpperComponents.map((component) => {                             
                                        return (<UpperComponent key={component.created_at} id={component.id} 
                                                   switchComponent={this.switchFocus} 
                                                   setCurrentPiece={this.setNewPiece} 
                                                   evaluatePiece={this.isOppositeComponentSuggested}
                                                   image={component.image}
                                                   toggleToPiece = {() => {if (LowerComponentEnabled === false){this.setState({LowerComponentEnabled: true})} else return; this.setState({currentLowerComponent: suggestedBottoms[0]})}}
                                                   isLowerComponentEnabled = {LowerComponentEnabled}
                                                   ref = {this.residingUpperComponent}
                                                   className = {currentComponent.whichPiece.whichType === 'match' ? 'PossibleMatches_Container' : currentComponent.whichPiece.whichType === 'bottom' ? 'standalonePiece' : 'standalonePiece'}/>
                                                )
                                        })
                                }
                            </TransitionGroup>
                            <TransitionGroup component = {PossibleMatches}>
                                {LowerComponents.map((component) => {
                                    return  (<LowerComponent key={component.created_at} id={component.id} 
                                               setCurrentPiece = {this.setNewPiece} 
                                               evaluatePiece={this.isOppositeComponentSuggested}
                                               image={component.image}
                                               toggleToPiece = {() => {if (UpperComponentEnabled === false){this.setState({UpperComponentEnabled: true})} else return; this.setState({currentUpperComponent: suggestedTops[0]})}}              
                                               switchComponent = {this.switchFocus}
                                               isUpperComponentEnabled = {UpperComponentEnabled}
                                               ref = {this.residingLowerComponent}
                                               className = {this.state.currentComponent.whichPiece.whichType === 'match' ? 'PossibleMatches_Container' : this.state.currentComponent.whichPiece.whichType === 'bottom' ? 'standalonePiece' : 'standalonePiece'}/>)                                                  
    
                                    })
                              }
                            </TransitionGroup>
                    </div>
                )
        }
    }
    
    render(){
    
    
        return(  
    
                <div className = 'GorClothingContainer'>
                  <Wardrobe upperComponent={this.state.currentComponent.whichPiece.currentUpperComponent} lowerComponent={this.state.currentComponent.whichPiece.currentLowerComponent} enableCapture={(snapshot) => this.snapshotMatch = snapshot} />
                  {this.renderDecision()}
                </div>
            );
    }
    
    function mapStateToProps(state){
        const { UpperComponents, LowerComponents, contemplated_piece, extraTops, extraBottoms, standaloneBottoms, standaloneTops, suggestedBottoms, suggestedTops } = state.possibleMatches;
        return {UpperComponents, LowerComponents, contemplated_piece, extraTops, extraBottoms, standaloneBottoms, standaloneTops, suggestedBottoms, suggestedTops };
     }
    
    export default connect(mapStateToProps, {defaultPieces, arrangePieces, getCorrespondingPieces, setEvaluatedPiece})(PossibleMatches)
    

    在我的actions/index.js中

    export function defaultPieces(){
        return function(dispatch){
            fetch(`${API_URL}/possible_matches/setup_possible_matches`, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            }).then((res) => res.json())
            .then((json) => {
                console.log('defaultPieces: ', json);
                dispatch(getInitialPieces(json))
            })
        }
    }
    
    export function getInitialPieces(request){
        return {
            type: INITIAL_PIECES,
            payload: request
        }
    }
    

    可能的齿轮减速器内部:

    import {INITIAL_PIECES, GET_ANCILLARY_PIECES, ORGANIZE_PIECES, SET_CONTEMPLATED_PIECE} from '../actions/types';
    
    const initialState = {
         UpperComponents: [],
         LowerComponents: [],
         contemplated_piece: null,
         extraTops: [],
         extraBottoms: [],
         standaloneTops: [],
         standaloneBottoms: [],
         suggestedTops: [],
         suggestedBottoms: []
    }
    
    export default function(state = initialState, action){
    
    
    switch(action.type){
        case INITIAL_PIECES:
            return {...state, {contemplated_piece: action.payload.contemplated_piece,
                              extraTops: action.payload.extra_tops,
                              extraBottoms: action.payload.extra_bottoms,
                              standaloneTops: action.payload.standalone_tops,
                              standaloneBottoms: action.payload.standalone_bottoms,
                              suggestedTops: action.payload.suggested_tops,
                              suggestedBottoms: action.payload.suggested_bottoms}
        case GET_ANCILLARY_PIECES:
               return {...state, extraTops: action.payload.extra_tops,
                                 extraBottoms: action.payload.extra_bottoms,
                                 standaloneTops: action.payload.standalone_tops,
                                 standaloneBottoms: action.payload.standalone_bottoms,
                                 suggestedTops: action.payload.suggested_tops,
                                 suggestedBottoms: action.payload.suggested_bottoms}
            case ORGANIZE_PIECES:
                   return {...state, UpperComponents: action.payload.UpperComponents,
                                     LowerComponents: action.payload.LowerComponents}           
            case SET_CONTEMPLATED_PIECE:
               return {...state, contemplated_piece: action.payload.contemplated_piece}
            default:
                return state;
    
    }
    

    }

    因为defaultpieces对于possiblematches组件不是有效的函数,所以它会干扰来自mapstatetoprops函数的uppercomponents属性的解释(用*表示)。

    奇怪的是,json从arrangepieces和defaultpieces方法中注销到控制台:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  0
  •   flo527    7 年前

        if (UpperComponents.length === 0){
            return;
        } else {
            this.setState({isFetched: true, isFetching: false});
        }
    

    componentWillReceiveProps(nextProps){
    
        if (nextProps.contemplated_piece !== this.props.contemplated_piece){
            if (nextProps.contemplated_piece.merch_type === 'top'){
                this.setState({currentLowerComponent: nextProps.suggestedBottoms[0], 
                        currentUpperComponent: nextProps.contemplated_piece});
            }
            else if (nextProps.contemplated_piece.merch_type === 'bottom'){
                this.setState({currentLowerComponent: nextProps.contemplated_piece,
                        currentUpperComponent: nextProps.suggestedTops[0]});
            }
        }
        else {
            return null;
        }
    }