ComponentDidMount更新状态,但似乎没有重新渲染组件

时间:2018-07-23 14:33:47

标签: reactjs

我面临的问题是,即使正在更新状态,componentDidMount似乎也不在重新渲染我的组件。许多代码即将发布,但它为我遇到的问题提供了背景信息。如果需要,我可以上传正在发生的事情的屏幕截图。

这是构造函数:

export class Upload extends React.Component<RouteComponentProps<{}>, UploadTaggingOptions> {

constructor(props: any) {
    super(props);
    this.state = {
        photographer: [
            { id: null, value: '', label: '' },
        ],
    };  
}

这里的组件确实挂载了:

componentDidMount {
    //Fetch request for photographers from the db
    fetch("http://localhost:49775/api/photographers")
        .then(res => res.json())
        .then((result) => {
            var photographerData = this.state!.photographer;
            var y = 0;
            //Remove the empty object first and foremost. The list should now be totally empty
            photographerData.shift();
            //The loop to add the galleries to the galleryData array
            for (var i in result) {
                var id = result[i].id;
                var value = result[i].firstname + ' ' + result[i].lastname;
                var label = value;
                var photographer = { "id": id, "value": value, "label": label };
                photographerData.push(photographer);
                y++;
            }


            this.setState({
                isLoaded: true,
                photographer: photographerData
            });

        },
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                });
                alert("Error loading options for the photographers. Refresh the page. If the error persists, please contact your administrator");
        }
    )

最后渲染:

 public render() {

    return <div>

        <div className="photographers"> 
            <p><b>Photographer:</b></p>
            <DropDown options={this.state!.photographer} />
        </div>
}

为清楚起见,屏幕上有更多组件(因此下拉组件有额外的div)。

我不确定为什么,但是下拉菜单显示的是我在构造函数中初始化的空白选项,componentdidupdate会执行获取请求,并将状态更新为已获取的数据,但是我必须按顺序单击空白值将这些数据值加载到下拉列表中。更改所选值而不是在状态更改后,几乎就像重新渲染一样。

我尝试过将这些请求移到构造函数中,但是存在相同的问题。也许

编辑:这是Dropdown组件的代码:

import * as React from 'react';
import Select from 'react-select';


const DropDown = (props: any) => {
    return (
        <div className="dropdown">
            <Select
                closeOnSelect={!(props.stayOpen)}
                disabled={props.disabled}
                options={props.options}
                placeholder="Select an option..."
                removeSelected={props.removeSelected}
                simpleValue
                value={props.selectedPhotographer}
                searchable={true}
                multi={true}
            />
        </div>
    )
}

export default DropDown;

1 个答案:

答案 0 :(得分:1)

来自React官方documentation

  

请不要直接更改this.state,因为之后调用setState()可能会替换您所做的更改。将此this.state视为不可变。

但是在您的代码中,您正在对其进行突变,尽管是通过分配给另一个变量来实现的:

var photographerData = this.state!.photographer;
// this DOES mutate the original array.
photographerData.shift();

这可能会干扰Reacts批处理更新策略,并可能导致延迟。

如果您不需要原始状态的数据,则可以执行以下操作:

var photographerData = [];

window.onload = function() {
  console.log('Testing');
  let testArr1 = [1, 2, 3]
  console.log('TestArr1 length before shift: ' + testArr1.length);
  let testArr2 = testArr1;
  testArr2.shift();
  console.log('TestArr1 length after shift: ' + testArr1.length);

}

相关问题