首页 > 解决方案 > 如何获取 fetch 调用的值以传递给我的组件并让组件重新呈现?

问题描述

我正在尝试构建一个 React 16.13.0 应用程序。我创建了以下FormContainer,在我在“componentDidMount”方法中加载数据后,我试图在prop变量(“建议”)中传递一个值......

class FormContainer extends Component {  
  static DEFAULT_COUNTRY = 484
  static REACT_APP_PROXY = process.env.REACT_APP_PROXY

  constructor(props) {
    super(props);

    this.state = {
      countries: [],
      provinces: [],
      errors: [],
      newCoop: {
        name: '',
        types: [{
          name: ''
        }],
        address: {
          formatted: '',
          locality: {
            name: '',
            postal_code: '',
            state: ''
          },
          country: FormContainer.DEFAULT_COUNTRY,
        },
        enabled: true,
        email: '',
        phone: '',
        web_site: '' 
      },

    }

...

  render() {
    return (
      <div>
        <form className="container-fluid" onSubmit={this.handleFormSubmit}>
            <FormGroup
                controlId="formBasicText">      

                <Input inputType={'text'}
                   title= {'Name'} 
                   name= {'name'}
                   value={this.state.newCoop.name} 
                   placeholder = {'Enter cooperative name'}
                   handleChange = {this.handleInput}
                   errors = {this.state.errors} 
                   /> {/* Name of the cooperative */}
 
                <CoopTypes 
                  name={'types'}
                  suggestions = {this.state.coopTypes} 
                  values = {this.state.newCoop.types}
                  placeholder = {'Enter coop type(s)'}
                  handleAddition = {this.handleCoopTypeAddition}
                  handleDeletion = {this.handleCoopTypeDeletion}
                  errors = {this.state.errors}
                /> {/* Coop Type Selection */}

        ...
  }

  componentDidMount() {
    let initialCountries = [];
    let initialProvinces = [];
    let coopTypes = [];
    ...
    // Get all possible coop types 
    fetch(FormContainer.REACT_APP_PROXY + '/coop_types/')
        .then(response => {
            return response.json();
        }).then(data => {
        coopTypes = data.map((coopType) => {
            return coopType
        });
        console.log("coop types:");
        console.log(coopTypes);
        this.setState({
            coopTypes: coopTypes,
        });
    });    
  }
}

下面是在表单中调用的组件定义...

class CoopTypes extends React.Component {
    constructor(props) {
        super(props);

        console.log("sugestions:");
        console.log(props.suggestions); 
        const tags = props.values.map(result => (
            {
                id: result.id,
                text: result.name
            }));
        this.state = {
            tags: tags,
            suggestions: props.values.map(result => ({
                id: result.id,
                text: result.name
            }))
        };
        this.handleDelete = props.handleDelete;
        this.handleAddition = props.handleAddition;
        this.handleDrag = this.handleDrag.bind(this);
    }
 
    handleDelete(i) {
        const { tags } = this.state;
        this.setState({
         tags: tags.filter((tag, index) => index !== i),
        });
    }
 
    handleAddition(tag) {
        this.setState(state => ({ tags: [...state.tags, tag] }));
    }
 
    handleDrag(tag, currPos, newPos) {
        const tags = [...this.state.tags];
        const newTags = tags.slice();
 
        newTags.splice(currPos, 1);
        newTags.splice(newPos, 0, tag);
 
        // re-render
        this.setState({ tags: newTags });
    }
 
    render() {
        const { tags, suggestions } = this.state;
        return (
            <div>
                <ReactTags tags={this.state.tags}
                    suggestions={this.state.suggestions}
                    handleDelete={this.handleDelete}
                    handleAddition={this.handleAddition}
                    handleDrag={this.handleDrag}
                    delimiters={delimiters} />
            </div>
        )
    }
};

export default CoopTypes;

问题是在“fetch”调用加载后,组件不会重新渲染。也就是说,它总是为建议道具呈现一个“null”值。我需要做什么才能在 fetch 调用加载后将值传递给组件?

标签: reactjscomponentsfetchrendering

解决方案


suggestions: props.values.map(result

  1. 使用了错误的道具,
  2. 更新的道具(如果更新)不会反映到状态(构造函数调用一次)

您可以直接在(使用局部变量)中使用props.suggestions( ),而无需在状态中“缓冲”(并处理道具更新)。使用功能组件可以更容易遵循 [dependencies]。.maprender

提示: 您可以放置console.log​​以render()确保它使用当前的建议道具呈现(或不呈现)。


这看起来有点奇怪:

    this.handleDelete = props.handleDelete;
    this.handleAddition = props.handleAddition;
    this.handleDrag = this.handleDrag.bind(this);

这看起来有点奇怪 - 你的类处理程序(handleDelete'handleAddition' 函数)是你的this.handleDeleteand this.handleAddition。用 props-handlers 覆盖它们(在构造函数中)有点 [no?] 意义。两个 this 处理程序都应该按原样绑定this.handleDrag。您可以使用 this-handlers 中的 props-handlers(有条件的,如果已定义)。


推荐阅读