在回调

时间:2018-04-06 09:26:13

标签: javascript reactjs

我已经读过setState我不应该直接componentDidMount,但是在回调中设置它很好(这就是为什么它是ajax的地方的原因调用)。 问题是我在解析了像这样的搜索参数之后设置了状态

componentDidMount() {
  let price = 0;

  const query = new URLSearchParams(this.props.location.search);
  for (let param of query.entries()) {
    if (param[0] === 'price') {
      price = param[1];
    }
  }

  this.setState({ price: price });
}

然后我执行条件渲染:如果价格未设置,我会渲染没有

据我所知,这将导致2次渲染:第一次渲染将为空白,第二次将是预期的渲染,在设定价格后。

那么,在setState内直接调用componentDidMount是否有任何问题?还有更好的选择吗?

由于最近的弃用,我不想使用componentWillMount(反应16.3)。

1 个答案:

答案 0 :(得分:0)

import java.util.HashMap;
import java.util.Map;

public class Refactoring {

    private static class IonStruct {};

    private static interface MessageBuilder {
        String  build(final String xId,final String yId, final IonStruct metadataStruct);
    }


    private static class NotActiveMessageBuilder implements MessageBuilder {

        private static final String YX_NON_ACTIVE_FMT = "Y %s X %s not active: status is inactive%n;";
        private static final String Y_NON_ACTIVE_FMT = "Y %s not active: status is inactive%n";

        @Override
        public String build(String xId, String yId, IonStruct metadataStruct) {
            return (xId != null) ? String.format(YX_NON_ACTIVE_FMT, yId, xId) : String.format(Y_NON_ACTIVE_FMT, yId) ;
        }

    }

    private static enum MessageTypeChine
    {
        instance();
        private final Map<String,MessageBuilder> builders;
        private MessageTypeChine() {
            this.builders = new HashMap<>();
            this.builders.put("NOT_ACTIVE", new NotActiveMessageBuilder());
        }

        public String constructMessage(final String reason, final String xId,
                final String yId, final IonStruct metadataStruct) {
            MessageBuilder builder = this.builders.get(reason);
            if(null != builder)
                return builder.build(xId, yId, metadataStruct);

            throw new UnsupportedOperationException("Message type is not supported");
        }
    }


    public static String constructMessage(final String reason, final String xId,
            final String yId, final IonStruct metadataStruct) {
        return MessageTypeChine.instance.constructMessage(reason, xId, yId, metadataStruct);
    }

}

现在创建一个函数

Application with identifier **** was not found in the directory botframework.com\r\nTrace ID

并且您可以在要显示/隐藏的div上使用条件渲染