Skip to content

Commit cdaf737

Browse files
committed
Serialize props when they're set rather than every time the component render code is called. Closes #226
This ensures that the props are only serialized once, rather than twice (once in the `Html.React` call and once in the `Html.ReactInitJavaScript` call)
1 parent df0313d commit cdaf737

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/React.Core/ReactComponent.cs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ public class ReactComponent : IReactComponent
3838
/// </summary>
3939
protected readonly IReactSiteConfiguration _configuration;
4040

41+
/// <summary>
42+
/// Raw props for this component
43+
/// </summary>
44+
protected object _props;
45+
46+
/// <summary>
47+
/// JSON serialized props for this component
48+
/// </summary>
49+
protected string _serializedProps;
50+
4151
/// <summary>
4252
/// Gets or sets the name of the component
4353
/// </summary>
@@ -61,7 +71,18 @@ public class ReactComponent : IReactComponent
6171
/// <summary>
6272
/// Gets or sets the props for this component
6373
/// </summary>
64-
public object Props { get; set; }
74+
public object Props
75+
{
76+
get { return _props; }
77+
set
78+
{
79+
_props = value;
80+
_serializedProps = JsonConvert.SerializeObject(
81+
value,
82+
_configuration.JsonSerializerSettings
83+
);
84+
}
85+
}
6586

6687
/// <summary>
6788
/// Initializes a new instance of the <see cref="ReactComponent"/> class.
@@ -166,11 +187,10 @@ protected virtual void EnsureComponentExists()
166187
/// <returns>JavaScript for component initialisation</returns>
167188
protected virtual string GetComponentInitialiser()
168189
{
169-
var encodedProps = JsonConvert.SerializeObject(Props, _configuration.JsonSerializerSettings); // SerializeObject accepts null settings
170190
return string.Format(
171191
"React.createElement({0}, {1})",
172192
ComponentName,
173-
encodedProps
193+
_serializedProps
174194
);
175195
}
176196

0 commit comments

Comments
 (0)