[英]Accessing Nested Method in React
我開發了我的第一個基於函數的 React 組件,現在我正在嘗試將其重構為基於類。 但是,在嘗試將其轉換時,我似乎無法使其正常工作。 我很確定問題出在 RenderItem 方法上,當我嘗試綁定它時,出現此錯誤: TypeError: Cannot read property 'bind' of undefined
。 如何綁定作為父方法的子方法的方法? 這是可能的,如果不是,什么是更好的解決方案?
編譯時報錯:
Line 35:10: 'state' is assigned a value but never used no-unused-vars
Line 51:9: 'renderItem' is assigned a value but never used no-unused-vars
import React, { useEffect, useReducer } from 'react'; import API from '@aws-amplify/api'; import { List } from 'antd'; import { listQuestions as ListQuestions } from '../../graphql/queries'; export default class QuestionLoader extends React.Component { state = { questions: [], loading: true, error: false, form: { asked: '', owner: '' }, }; constructor() { super(); this.GetQuestion = this.GetQuestion.bind(this); this.reducer = this.reducer.bind(this); // this.renderItem = this.renderItem.bind(this); console.log('constructor', this); } reducer(state, action) { switch (action.type) { case 'SET_QUESTIONS': return { ...state, questions: action.questions, loading: false }; case 'ERROR': return { ...state, loading: false, error: true }; default: return state; } } GetQuestion() { const [state, dispatch] = useReducer(this.reducer, this.state); useEffect(() => { fetchQuestions(); }, []); async function fetchQuestions() { try { const questionData = await API.graphql({ query: ListQuestions }); dispatch({ type: 'SET_QUESTIONS', questions: questionData.data.listQuestions.items }); } catch (err) { console.log('error: ', err); dispatch({ type: 'ERROR' }); } } const renderItem = (item) => { console.log(this); return <List.Item.Meta title={item.asked} description={item.owner} />; }; } render() { return ( <div> <List loading={this.state.loading} dataSource={this.state.questions} renderItem={this.renderItem} /> </div> ); } } // export default QuestionLoader;
你不能混合功能組件和類組件的東西。 useEffect、useReducer 與類組件一起使用是錯誤的。
不要使用綁定,使用箭頭函數來創建方法。 刪除構造函數。
import React from 'react';
export default class QuestionLoader extends React.Component {
state = {
data: "name"
};
handleClick = () => {
this.setState({
name:"test"
})
}
render() {
return (<div> {this.state.name}
<button onClick={this.handleClick}></button>
</div>
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.